diff --git a/tasks/price-index/price-index-basket-indices-d1-e0000/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-e0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-e0000/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-e0000/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..3c4aefc520be984bafe681e71c1e77bd42c4df52 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0000/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +pasta,2016,1.48,191,kg +pasta,2017,1.48,191,kg +pasta,2018,1.55,194,kg +butter,2016,6.74,10,kg +butter,2017,6.58,10,kg +butter,2018,7.17,9,kg +tea,2016,16.04,160,kg +tea,2017,16.45,154,kg +tea,2018,18.25,150,kg +coffee,2016,12.20,13,kg +coffee,2017,11.73,14,kg +coffee,2018,12.51,14,kg +cheese,2016,11.41,138,kg +cheese,2017,12.13,134,kg +cheese,2018,11.75,128,kg diff --git a/tasks/price-index/price-index-basket-indices-d1-e0000/instruction.md b/tasks/price-index/price-index-basket-indices-d1-e0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96ec0d95cc5f1f0e71b1d9b0cd01fbdf9c094283 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0000/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2016, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2016"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-e0000/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-e0000/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0000/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-e0000/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-e0000/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0000/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d1-e0012/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-e0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-e0012/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-e0012/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..fc36e5cc9166dff8c93657c2aa72ebf85146d8b5 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0012/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +rice,2012,2.58,103,kg +rice,2013,2.51,101,kg +rice,2014,2.83,100,kg +potatoes,2012,1.68,99,kg +potatoes,2013,1.79,97,kg +potatoes,2014,1.75,100,kg +coffee,2012,13.50,186,kg +coffee,2013,14.03,170,kg +coffee,2014,15.32,161,kg +butter,2012,9.93,71,kg +butter,2013,9.87,75,kg +butter,2014,9.78,78,kg +eggs,2012,0.35,732,each +eggs,2013,0.36,727,each +eggs,2014,0.36,744,each diff --git a/tasks/price-index/price-index-basket-indices-d1-e0012/instruction.md b/tasks/price-index/price-index-basket-indices-d1-e0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..be4748ee916dda11e12939578724b44c0b8ce026 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0012/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2012, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2012"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-e0012/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-e0012/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0012/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-e0012/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-e0012/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-e0012/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d1-t0000/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-t0000/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-t0000/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..587259b41553c378baaa6562c10a384f52ec1308 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0000/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +coffee,2010,9.04,166,kg +coffee,2011,9.89,165,kg +coffee,2012,10.91,165,kg +sugar,2010,1.42,18,kg +sugar,2011,1.52,17,kg +sugar,2012,1.65,17,kg +olive oil,2010,8.77,167,litre +olive oil,2011,9.65,165,litre +olive oil,2012,9.90,160,litre +pasta,2010,1.98,28,kg +pasta,2011,2.00,28,kg +pasta,2012,2.25,26,kg +bread,2010,2.45,34,kg +bread,2011,2.71,32,kg +bread,2012,2.94,32,kg diff --git a/tasks/price-index/price-index-basket-indices-d1-t0000/instruction.md b/tasks/price-index/price-index-basket-indices-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ad6bf1e2943abdc7f683ba694b523f3b545571c --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0000/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2010, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2010"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-t0000/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-t0000/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0000/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-t0000/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-t0000/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0000/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d1-t0012/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-t0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-t0012/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-t0012/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..3ffe1caa8fc4c7d415c7eabcc740d41f31d9f8c3 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0012/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +tea,2019,15.11,80,kg +tea,2020,16.20,72,kg +tea,2021,16.19,67,kg +rice,2019,2.73,159,kg +rice,2020,2.63,154,kg +rice,2021,2.88,153,kg +cheese,2019,9.60,78,kg +cheese,2020,10.39,73,kg +cheese,2021,10.16,71,kg +butter,2019,10.09,175,kg +butter,2020,10.05,171,kg +butter,2021,10.12,163,kg +olive oil,2019,9.64,134,litre +olive oil,2020,9.32,140,litre +olive oil,2021,9.68,131,litre diff --git a/tasks/price-index/price-index-basket-indices-d1-t0012/instruction.md b/tasks/price-index/price-index-basket-indices-d1-t0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87a2cccce92316c558337c7cd98589c3df3ca9c5 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0012/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2019, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2019"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-t0012/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-t0012/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0012/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-t0012/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-t0012/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0012/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d1-t0024/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-t0024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0024/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-t0024/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-t0024/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..5ed9f437bb86f119f401c899016f37ee7d26fbd4 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0024/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +rice,2013,2.80,148,kg +rice,2014,3.15,129,kg +rice,2015,3.52,118,kg +chicken,2013,8.18,253,kg +chicken,2014,8.52,250,kg +chicken,2015,9.54,244,kg +yoghurt,2013,4.17,229,kg +yoghurt,2014,4.26,213,kg +yoghurt,2015,4.69,197,kg +pasta,2013,1.79,210,kg +pasta,2014,1.88,216,kg +pasta,2015,2.09,193,kg +milk,2013,0.97,62,litre +milk,2014,1.07,60,litre +milk,2015,1.14,59,litre diff --git a/tasks/price-index/price-index-basket-indices-d1-t0024/instruction.md b/tasks/price-index/price-index-basket-indices-d1-t0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d775c9afb8ad37a27649cb0d74ac7d097287cee5 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0024/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2013, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2013"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-t0024/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-t0024/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0024/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-t0024/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-t0024/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0024/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d1-t0036/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0036/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-t0036/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-t0036/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..f9dec6d1f721fd86dcb186d6aafcbca15f37f9c0 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0036/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +bread,2016,2.64,189,kg +bread,2017,2.62,193,kg +bread,2018,2.68,195,kg +rice,2016,1.76,181,kg +rice,2017,1.99,166,kg +rice,2018,2.22,149,kg +sugar,2016,1.19,249,kg +sugar,2017,1.33,227,kg +sugar,2018,1.33,240,kg +apples,2016,2.38,223,kg +apples,2017,2.40,232,kg +apples,2018,2.34,242,kg +potatoes,2016,1.07,14,kg +potatoes,2017,1.18,13,kg +potatoes,2018,1.19,14,kg diff --git a/tasks/price-index/price-index-basket-indices-d1-t0036/instruction.md b/tasks/price-index/price-index-basket-indices-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96ec0d95cc5f1f0e71b1d9b0cd01fbdf9c094283 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0036/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2016, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2016"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-t0036/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-t0036/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0036/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-t0036/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-t0036/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0036/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d1-t0048/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-t0048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0048/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-t0048/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-t0048/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..8a34fad1004b6089e8b65349c9786743a3a2e3b5 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0048/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +coffee,2012,10.69,165,kg +coffee,2013,11.83,159,kg +coffee,2014,12.96,143,kg +orange juice,2012,1.98,19,litre +orange juice,2013,2.00,18,litre +orange juice,2014,2.24,16,litre +yoghurt,2012,4.46,16,kg +yoghurt,2013,4.70,16,kg +yoghurt,2014,4.64,15,kg +chicken,2012,7.12,152,kg +chicken,2013,7.31,158,kg +chicken,2014,7.26,157,kg +sugar,2012,1.55,214,kg +sugar,2013,1.76,204,kg +sugar,2014,1.87,190,kg diff --git a/tasks/price-index/price-index-basket-indices-d1-t0048/instruction.md b/tasks/price-index/price-index-basket-indices-d1-t0048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..be4748ee916dda11e12939578724b44c0b8ce026 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0048/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2012, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2012"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-t0048/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-t0048/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0048/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-t0048/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-t0048/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0048/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d1-t0060/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-t0060/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0060/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-t0060/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-t0060/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..609cfcf662c8021dff39f4e04d8fd2dd910e7889 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0060/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +eggs,2014,0.26,744,each +eggs,2015,0.28,678,each +eggs,2016,0.29,628,each +yoghurt,2014,3.71,29,kg +yoghurt,2015,3.85,29,kg +yoghurt,2016,3.78,31,kg +chicken,2014,5.90,8,kg +chicken,2015,6.07,8,kg +chicken,2016,6.38,8,kg +sugar,2014,1.76,115,kg +sugar,2015,1.93,105,kg +sugar,2016,2.01,101,kg +apples,2014,2.23,215,kg +apples,2015,2.30,209,kg +apples,2016,2.29,207,kg diff --git a/tasks/price-index/price-index-basket-indices-d1-t0060/instruction.md b/tasks/price-index/price-index-basket-indices-d1-t0060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4aa7578e8231d43b5c3476fcd37287ad1fa2e43 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0060/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2014, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2014"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-t0060/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-t0060/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0060/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-t0060/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-t0060/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0060/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d1-t0072/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d1-t0072/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0072/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d1-t0072/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d1-t0072/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..179c23604921f42c1aba2145c76813e7ed5b5505 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0072/environment/workdir/basket.csv @@ -0,0 +1,16 @@ +item,period,price,quantity,unit +orange juice,2015,2.60,233,litre +orange juice,2016,2.87,205,litre +orange juice,2017,2.79,217,litre +potatoes,2015,1.25,118,kg +potatoes,2016,1.35,113,kg +potatoes,2017,1.41,109,kg +yoghurt,2015,2.94,133,kg +yoghurt,2016,3.01,131,kg +yoghurt,2017,3.29,117,kg +coffee,2015,11.62,108,kg +coffee,2016,12.83,104,kg +coffee,2017,13.62,102,kg +olive oil,2015,5.89,107,litre +olive oil,2016,6.22,110,litre +olive oil,2017,7.03,106,litre diff --git a/tasks/price-index/price-index-basket-indices-d1-t0072/instruction.md b/tasks/price-index/price-index-basket-indices-d1-t0072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a3ce339476b7355c71025d89e43875dfc018275 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0072/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 3 years. Prices are in crowns (CRN). + +The base year is 2015, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2015"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 3 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d1-t0072/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d1-t0072/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0072/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d1-t0072/tests/verify.py b/tasks/price-index/price-index-basket-indices-d1-t0072/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d1-t0072/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-e0004/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-e0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-e0004/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-e0004/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..5bf2de749d60b8fef1ee49cebc2d96de4f222423 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0004/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +rice,2021,supermarket,0.21,ORO,29,kg +eggs,2020,supermarket,0.05,ORO,481,each +tea,2022,corner shop,17.05,CRN,181,kg +yoghurt,2020,online,0.39,ORO,170,kg +yoghurt,2019,supermarket,0.35,ORO,191,kg +bread,2022,supermarket,3.35,CRN,198,kg +cheese,2019,online,7.36,CRN,141,kg +rice,2019,market stall,0.17,ORO,36,kg +tea,2021,corner shop,16.79,CRN,185,kg +olive oil,2020,corner shop,8.71,CRN,132,litre +coffee,2020,market stall,12.78,CRN,243,kg +tea,2019,supermarket,15.78,CRN,186,kg +coffee,2021,supermarket,12.97,CRN,246,kg +bread,2020,market stall,3.05,CRN,220,kg +olive oil,2022,market stall,9.63,CRN,118,litre +eggs,2019,corner shop,0.05,ORO,492,each +cheese,2020,online,7.86,CRN,132,kg +bread,2021,corner shop,3.01,CRN,210,kg +coffee,2022,online,12.92,CRN,260,kg +olive oil,2019,corner shop,8.97,CRN,127,litre +olive oil,2021,corner shop,9.15,CRN,123,litre +rice,2020,supermarket,0.18,ORO,33,kg +eggs,2021,supermarket,0.05,ORO,450,each +eggs,2022,online,0.05,ORO,408,each +yoghurt,2022,online,0.36,ORO,171,kg +tea,2020,corner shop,16.52,CRN,182,kg +rice,2022,corner shop,0.20,ORO,30,kg +bread,2019,online,3.03,CRN,217,kg +coffee,2019,corner shop,12.19,CRN,243,kg +cheese,2022,corner shop,9.61,CRN,113,kg +yoghurt,2021,market stall,0.38,ORO,167,kg +cheese,2021,supermarket,8.72,CRN,115,kg diff --git a/tasks/price-index/price-index-basket-indices-d2-e0004/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-e0004/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..869959b8860367c5a471d69ae03baa2e7d22bfaf --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0004/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2019,ORO,10.1586 +2020,ORO,9.5907 +2021,ORO,9.4958 +2022,ORO,9.6154 +2019,ZED,7.2856 +2020,ZED,7.8882 +2021,ZED,8.0473 +2022,ZED,8.5266 diff --git a/tasks/price-index/price-index-basket-indices-d2-e0004/instruction.md b/tasks/price-index/price-index-basket-indices-d2-e0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6e35c6c04bc86303ee15a579e049c4f2a36d335 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0004/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2019, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2019"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-e0004/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-e0004/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0004/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-e0004/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-e0004/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0004/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-e0016/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-e0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-e0016/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-e0016/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..b6ddbe9b685ca41265c2e7c78c2797067c4a069d --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0016/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +coffee,2012,market stall,4.03,ORO,197,kg +butter,2013,corner shop,6.91,CRN,182,kg +sugar,2014,online,1.75,CRN,80,kg +orange juice,2013,supermarket,2.31,CRN,98,litre +apples,2011,corner shop,2.67,CRN,209,kg +pasta,2012,online,1.67,CRN,145,kg +cheese,2014,supermarket,4.04,ORO,50,kg +apples,2013,online,2.89,CRN,179,kg +coffee,2014,corner shop,4.63,ORO,210,kg +butter,2014,corner shop,7.39,CRN,186,kg +coffee,2011,supermarket,3.57,ORO,225,kg +pasta,2011,online,1.50,CRN,147,kg +coffee,2013,market stall,4.30,ORO,198,kg +cheese,2013,supermarket,3.52,ORO,53,kg +rice,2014,market stall,0.21,ZED,145,kg +sugar,2013,market stall,1.71,CRN,78,kg +pasta,2014,corner shop,1.58,CRN,149,kg +rice,2013,corner shop,0.21,ZED,153,kg +apples,2012,online,2.93,CRN,185,kg +butter,2011,market stall,6.43,CRN,197,kg +rice,2012,market stall,0.21,ZED,147,kg +orange juice,2014,online,2.28,CRN,94,litre +sugar,2011,market stall,1.72,CRN,78,kg +orange juice,2012,corner shop,2.10,CRN,100,litre +apples,2014,supermarket,3.14,CRN,177,kg +cheese,2011,market stall,3.23,ORO,58,kg +cheese,2012,market stall,3.20,ORO,58,kg +pasta,2013,supermarket,1.61,CRN,138,kg +butter,2012,corner shop,6.90,CRN,176,kg +rice,2011,online,0.22,ZED,147,kg +orange juice,2011,market stall,2.17,CRN,104,litre +sugar,2012,market stall,1.65,CRN,75,kg diff --git a/tasks/price-index/price-index-basket-indices-d2-e0016/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-e0016/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..0c5a3b1b3e039da063d841af5cf28a9c974ce4bf --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0016/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2011,ORO,3.4671 +2012,ORO,3.4186 +2013,ORO,3.4153 +2014,ORO,3.1943 +2011,ZED,8.9848 +2012,ZED,9.8027 +2013,ZED,10.2001 +2014,ZED,10.7966 diff --git a/tasks/price-index/price-index-basket-indices-d2-e0016/instruction.md b/tasks/price-index/price-index-basket-indices-d2-e0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..98b89d48ef0d798362b35d7225e8d2bf4a11cc2f --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0016/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2011, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2011"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-e0016/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-e0016/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0016/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-e0016/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-e0016/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-e0016/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-t0004/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-t0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-t0004/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-t0004/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..84ed3aadcf1537e15b2c2dc62a9a2c7ae3482e01 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0004/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +apples,2021,market stall,3.45,CRN,244,kg +bread,2022,online,0.57,ZED,236,kg +apples,2019,supermarket,3.09,CRN,252,kg +potatoes,2019,supermarket,1.00,CRN,105,kg +bread,2021,market stall,0.60,ZED,229,kg +sugar,2019,supermarket,1.36,CRN,58,kg +orange juice,2019,supermarket,0.33,ZED,123,litre +olive oil,2022,corner shop,0.65,ORO,164,litre +pasta,2020,market stall,1.87,CRN,63,kg +pasta,2019,online,1.67,CRN,64,kg +potatoes,2022,market stall,1.23,CRN,86,kg +coffee,2022,corner shop,9.16,CRN,73,kg +sugar,2022,corner shop,1.41,CRN,60,kg +pasta,2022,supermarket,2.27,CRN,59,kg +bread,2019,online,0.55,ZED,245,kg +olive oil,2021,online,0.65,ORO,158,litre +olive oil,2019,corner shop,0.67,ORO,155,litre +sugar,2021,supermarket,1.46,CRN,58,kg +apples,2020,online,3.13,CRN,257,kg +coffee,2021,market stall,8.55,CRN,72,kg +orange juice,2022,corner shop,0.37,ZED,125,litre +pasta,2021,corner shop,2.11,CRN,62,kg +bread,2020,corner shop,0.61,ZED,232,kg +orange juice,2020,corner shop,0.35,ZED,123,litre +coffee,2019,market stall,8.98,CRN,77,kg +potatoes,2021,supermarket,1.24,CRN,92,kg +sugar,2020,supermarket,1.37,CRN,59,kg +apples,2022,market stall,3.70,CRN,242,kg +orange juice,2021,supermarket,0.36,ZED,130,litre +potatoes,2020,corner shop,1.10,CRN,101,kg +coffee,2020,market stall,8.64,CRN,76,kg +olive oil,2020,supermarket,0.68,ORO,158,litre diff --git a/tasks/price-index/price-index-basket-indices-d2-t0004/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-t0004/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..f179cd6219d86abe327d362fd56793e2c5f19a55 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0004/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2019,ORO,9.6391 +2020,ORO,9.5349 +2021,ORO,10.0653 +2022,ORO,10.1930 +2019,ZED,7.0643 +2020,ZED,6.5601 +2021,ZED,6.4347 +2022,ZED,6.8461 diff --git a/tasks/price-index/price-index-basket-indices-d2-t0004/instruction.md b/tasks/price-index/price-index-basket-indices-d2-t0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6e35c6c04bc86303ee15a579e049c4f2a36d335 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0004/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2019, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2019"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-t0004/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-t0004/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0004/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-t0004/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-t0004/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0004/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-t0016/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-t0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-t0016/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-t0016/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..9e695a6a599c51e324088baa50e024a8a9fdca2b --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0016/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +potatoes,2021,corner shop,1.27,CRN,104,kg +butter,2020,market stall,1.69,ORO,128,kg +olive oil,2019,supermarket,5.93,CRN,217,litre +coffee,2021,market stall,14.30,CRN,175,kg +butter,2022,corner shop,1.54,ORO,139,kg +apples,2020,online,3.39,CRN,126,kg +apples,2022,market stall,3.84,CRN,118,kg +apples,2021,online,3.82,CRN,112,kg +yoghurt,2019,corner shop,4.17,CRN,238,kg +cheese,2022,online,1.11,ZED,103,kg +olive oil,2021,supermarket,7.05,CRN,194,litre +olive oil,2020,online,6.70,CRN,204,litre +bread,2022,online,0.53,ZED,242,kg +coffee,2022,online,15.75,CRN,174,kg +cheese,2021,supermarket,1.04,ZED,100,kg +butter,2019,supermarket,1.49,ORO,139,kg +yoghurt,2020,supermarket,4.53,CRN,229,kg +olive oil,2022,online,7.81,CRN,178,litre +cheese,2019,online,1.02,ZED,103,kg +potatoes,2019,supermarket,1.19,CRN,103,kg +yoghurt,2022,corner shop,5.13,CRN,217,kg +bread,2021,online,0.48,ZED,270,kg +yoghurt,2021,market stall,5.00,CRN,222,kg +bread,2019,market stall,0.47,ZED,259,kg +coffee,2020,online,13.27,CRN,188,kg +coffee,2019,corner shop,12.74,CRN,200,kg +bread,2020,online,0.44,ZED,259,kg +potatoes,2022,corner shop,1.33,CRN,106,kg +butter,2021,online,1.57,ORO,136,kg +apples,2019,supermarket,3.23,CRN,124,kg +potatoes,2020,supermarket,1.18,CRN,106,kg +cheese,2020,online,1.01,ZED,95,kg diff --git a/tasks/price-index/price-index-basket-indices-d2-t0016/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-t0016/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..a69e35ff6260795f753180cde0dfaed35ab742ed --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0016/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2019,ORO,7.0685 +2020,ORO,7.0014 +2021,ORO,7.4396 +2022,ORO,7.7420 +2019,ZED,8.1310 +2020,ZED,8.6350 +2021,ZED,8.0420 +2022,ZED,7.9319 diff --git a/tasks/price-index/price-index-basket-indices-d2-t0016/instruction.md b/tasks/price-index/price-index-basket-indices-d2-t0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6e35c6c04bc86303ee15a579e049c4f2a36d335 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0016/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2019, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2019"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-t0016/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-t0016/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0016/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-t0016/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-t0016/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0016/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-t0028/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-t0028/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0028/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-t0028/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-t0028/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..37f2931027c41d8cddff0859abcae75e63105dcf --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0028/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +butter,2013,online,6.93,CRN,110,kg +pasta,2011,supermarket,1.95,CRN,212,kg +olive oil,2014,corner shop,8.02,CRN,108,litre +sugar,2011,online,1.66,CRN,46,kg +apples,2012,market stall,2.89,CRN,84,kg +bread,2011,supermarket,0.37,ZED,86,kg +chicken,2012,supermarket,1.46,ORO,171,kg +bread,2013,online,0.38,ZED,83,kg +sugar,2014,supermarket,1.85,CRN,41,kg +butter,2011,online,6.65,CRN,112,kg +butter,2014,online,7.75,CRN,97,kg +tea,2013,online,1.68,ZED,9,kg +apples,2014,supermarket,3.49,CRN,74,kg +pasta,2012,corner shop,1.88,CRN,228,kg +olive oil,2012,corner shop,7.15,CRN,118,litre +tea,2012,online,1.56,ZED,10,kg +bread,2014,market stall,0.42,ZED,84,kg +pasta,2013,corner shop,1.80,CRN,235,kg +chicken,2014,online,1.59,ORO,154,kg +chicken,2013,online,1.67,ORO,165,kg +chicken,2011,online,1.44,ORO,177,kg +tea,2011,market stall,1.50,ZED,11,kg +sugar,2013,online,1.84,CRN,40,kg +pasta,2014,supermarket,1.88,CRN,225,kg +apples,2013,corner shop,3.16,CRN,79,kg +tea,2014,corner shop,2.02,ZED,8,kg +butter,2012,online,6.72,CRN,119,kg +bread,2012,supermarket,0.38,ZED,85,kg +olive oil,2011,supermarket,6.65,CRN,133,litre +olive oil,2013,corner shop,7.85,CRN,117,litre +sugar,2012,corner shop,1.78,CRN,42,kg +apples,2011,market stall,2.94,CRN,82,kg diff --git a/tasks/price-index/price-index-basket-indices-d2-t0028/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-t0028/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..a98d610e49fa3444b460958c79c9ee3a4fe77b05 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0028/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2011,ORO,5.1747 +2012,ORO,5.3704 +2013,ORO,5.3483 +2014,ORO,5.6504 +2011,ZED,8.6655 +2012,ZED,9.1159 +2013,ZED,9.1228 +2014,ZED,8.5000 diff --git a/tasks/price-index/price-index-basket-indices-d2-t0028/instruction.md b/tasks/price-index/price-index-basket-indices-d2-t0028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..98b89d48ef0d798362b35d7225e8d2bf4a11cc2f --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0028/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2011, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2011"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-t0028/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-t0028/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0028/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-t0028/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-t0028/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0028/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-t0040/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-t0040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0040/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-t0040/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-t0040/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..f1bf1dea38ac1af3c5f48939c2dc8c8ebfbd5ad0 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0040/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +cheese,2018,online,12.44,CRN,175,kg +potatoes,2017,online,0.20,ZED,188,kg +milk,2016,online,0.14,ORO,213,litre +pasta,2018,market stall,0.18,ZED,149,kg +bread,2018,market stall,2.92,CRN,211,kg +apples,2017,corner shop,3.02,CRN,185,kg +rice,2017,market stall,1.69,CRN,69,kg +bread,2016,market stall,2.79,CRN,224,kg +bread,2017,online,3.02,CRN,198,kg +cheese,2017,corner shop,12.77,CRN,169,kg +potatoes,2018,online,0.18,ZED,183,kg +rice,2019,online,1.96,CRN,64,kg +cheese,2019,online,13.70,CRN,165,kg +pasta,2019,corner shop,0.19,ZED,133,kg +milk,2019,corner shop,0.16,ORO,177,litre +potatoes,2019,online,0.20,ZED,165,kg +apples,2019,supermarket,3.36,CRN,169,kg +sugar,2019,market stall,1.79,CRN,189,kg +milk,2018,corner shop,0.17,ORO,180,litre +sugar,2018,supermarket,1.83,CRN,186,kg +potatoes,2016,supermarket,0.19,ZED,207,kg +milk,2017,supermarket,0.16,ORO,200,litre +bread,2019,market stall,3.32,CRN,189,kg +rice,2016,supermarket,1.66,CRN,74,kg +rice,2018,supermarket,1.74,CRN,69,kg +apples,2018,supermarket,3.03,CRN,174,kg +pasta,2016,market stall,0.20,ZED,169,kg +apples,2016,market stall,3.10,CRN,173,kg +pasta,2017,corner shop,0.19,ZED,156,kg +sugar,2016,supermarket,1.62,CRN,212,kg +sugar,2017,corner shop,1.67,CRN,208,kg +cheese,2016,corner shop,11.39,CRN,184,kg diff --git a/tasks/price-index/price-index-basket-indices-d2-t0040/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-t0040/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..4eb4add9e34a42d1965a9977dcc42100a7551dc7 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0040/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2016,ORO,7.1692 +2017,ORO,6.8616 +2018,ORO,6.9805 +2019,ORO,7.4626 +2016,ZED,7.5155 +2017,ZED,8.0940 +2018,ZED,8.7072 +2019,ZED,8.7205 diff --git a/tasks/price-index/price-index-basket-indices-d2-t0040/instruction.md b/tasks/price-index/price-index-basket-indices-d2-t0040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..889c92afceb33907ccb13de884ee84f2bc5d0bd3 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0040/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2016, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2016"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-t0040/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-t0040/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0040/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-t0040/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-t0040/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0040/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-t0052/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-t0052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0052/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-t0052/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-t0052/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..ba8c68b61ff969def380cb7e52486532d8161535 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0052/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +milk,2017,market stall,1.21,CRN,105,litre +apples,2016,online,3.16,CRN,14,kg +olive oil,2017,supermarket,0.66,ZED,172,litre +tea,2017,supermarket,18.52,CRN,157,kg +eggs,2017,supermarket,0.05,ORO,1070,each +apples,2019,online,4.26,CRN,11,kg +olive oil,2019,online,0.61,ZED,192,litre +eggs,2019,online,0.05,ORO,1160,each +milk,2018,online,1.37,CRN,99,litre +olive oil,2018,market stall,0.64,ZED,178,litre +bread,2019,supermarket,3.63,CRN,151,kg +olive oil,2016,supermarket,0.64,ZED,176,litre +eggs,2016,corner shop,0.05,ORO,1164,each +apples,2017,corner shop,3.56,CRN,14,kg +bread,2018,online,3.76,CRN,149,kg +butter,2016,supermarket,0.91,ZED,98,kg +butter,2018,corner shop,0.97,ZED,97,kg +tea,2016,online,17.52,CRN,175,kg +bread,2017,online,3.88,CRN,142,kg +butter,2017,online,0.97,ZED,94,kg +eggs,2018,online,0.05,ORO,1085,each +rice,2019,supermarket,2.60,CRN,84,kg +rice,2017,corner shop,2.43,CRN,92,kg +tea,2018,supermarket,19.55,CRN,162,kg +tea,2019,corner shop,20.67,CRN,156,kg +butter,2019,online,0.96,ZED,90,kg +apples,2018,supermarket,3.86,CRN,12,kg +rice,2018,market stall,2.59,CRN,83,kg +bread,2016,online,3.79,CRN,149,kg +milk,2019,online,1.43,CRN,97,litre +rice,2016,market stall,2.18,CRN,93,kg +milk,2016,corner shop,1.21,CRN,100,litre diff --git a/tasks/price-index/price-index-basket-indices-d2-t0052/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-t0052/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..f40a8317af4f6b7c534398c18d589eb03bb421fd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0052/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2016,ORO,7.5520 +2017,ORO,7.1620 +2018,ORO,7.7319 +2019,ORO,8.1627 +2016,ZED,9.0525 +2017,ZED,9.0520 +2018,ZED,9.6197 +2019,ZED,9.8733 diff --git a/tasks/price-index/price-index-basket-indices-d2-t0052/instruction.md b/tasks/price-index/price-index-basket-indices-d2-t0052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..889c92afceb33907ccb13de884ee84f2bc5d0bd3 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0052/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2016, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2016"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-t0052/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-t0052/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0052/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-t0052/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-t0052/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0052/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-t0064/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-t0064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0064/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-t0064/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-t0064/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..f4e258c7ba36ca9817e7b46b9b21b8c11ece9e50 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0064/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +tea,2017,online,13.01,CRN,219,kg +butter,2015,online,8.98,CRN,258,kg +cheese,2016,online,3.75,ZED,259,kg +sugar,2016,market stall,0.78,ZED,235,kg +chicken,2018,online,7.04,CRN,48,kg +coffee,2017,supermarket,13.48,CRN,219,kg +eggs,2017,market stall,0.05,ORO,1211,each +chicken,2017,supermarket,7.14,CRN,45,kg +butter,2016,supermarket,9.60,CRN,235,kg +sugar,2018,market stall,0.85,ZED,198,kg +sugar,2015,corner shop,0.77,ZED,229,kg +yoghurt,2015,market stall,3.21,CRN,233,kg +cheese,2017,market stall,3.50,ZED,277,kg +tea,2018,online,14.39,CRN,219,kg +tea,2015,corner shop,11.34,CRN,246,kg +butter,2017,market stall,10.15,CRN,218,kg +eggs,2015,supermarket,0.05,ORO,1344,each +yoghurt,2017,supermarket,3.43,CRN,234,kg +cheese,2018,supermarket,3.83,ZED,262,kg +chicken,2016,supermarket,6.72,CRN,45,kg +coffee,2018,corner shop,15.28,CRN,192,kg +coffee,2016,market stall,12.81,CRN,227,kg +eggs,2016,supermarket,0.05,ORO,1229,each +yoghurt,2018,online,3.76,CRN,217,kg +cheese,2015,corner shop,3.69,ZED,250,kg +eggs,2018,corner shop,0.05,ORO,1254,each +sugar,2017,supermarket,0.77,ZED,220,kg +coffee,2015,online,12.82,CRN,218,kg +chicken,2015,market stall,6.49,CRN,47,kg +butter,2018,supermarket,11.37,CRN,213,kg +yoghurt,2016,market stall,3.51,CRN,219,kg +tea,2016,online,11.51,CRN,232,kg diff --git a/tasks/price-index/price-index-basket-indices-d2-t0064/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-t0064/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..c9146f51a537c7341fd0332c973b77690daa34df --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0064/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2015,ORO,9.6183 +2016,ORO,9.9190 +2017,ORO,10.4514 +2018,ORO,10.3146 +2015,ZED,2.1295 +2016,ZED,2.1640 +2017,ZED,2.2805 +2018,ZED,2.3018 diff --git a/tasks/price-index/price-index-basket-indices-d2-t0064/instruction.md b/tasks/price-index/price-index-basket-indices-d2-t0064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b425b1f7925cb8df58505c3945a27ff89fc04229 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0064/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2015, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2015"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-t0064/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-t0064/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0064/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-t0064/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-t0064/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0064/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d2-t0076/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d2-t0076/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0076/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d2-t0076/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d2-t0076/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..68d93379659984e3b8dc114b44678f52ae45891e --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0076/environment/workdir/basket.csv @@ -0,0 +1,33 @@ +item,period,outlet,price,currency,quantity,unit +sugar,2020,supermarket,1.17,CRN,13,kg +cheese,2020,corner shop,11.70,CRN,57,kg +rice,2020,market stall,2.07,CRN,217,kg +apples,2020,supermarket,2.46,CRN,82,kg +rice,2019,online,1.86,CRN,228,kg +cheese,2021,supermarket,12.09,CRN,54,kg +eggs,2021,market stall,0.40,CRN,166,each +eggs,2020,online,0.36,CRN,188,each +bread,2022,corner shop,0.67,ORO,159,kg +sugar,2021,supermarket,1.14,CRN,13,kg +apples,2019,online,2.22,CRN,90,kg +butter,2022,corner shop,1.99,ORO,197,kg +sugar,2019,supermarket,1.20,CRN,13,kg +bread,2021,supermarket,0.61,ORO,165,kg +coffee,2020,corner shop,3.16,ORO,63,kg +bread,2020,market stall,0.60,ORO,171,kg +sugar,2022,market stall,1.25,CRN,12,kg +apples,2022,online,2.99,CRN,65,kg +eggs,2019,online,0.35,CRN,180,each +coffee,2019,market stall,2.98,ORO,69,kg +apples,2021,online,2.64,CRN,74,kg +coffee,2022,corner shop,3.31,ORO,65,kg +butter,2019,online,1.46,ORO,242,kg +eggs,2022,supermarket,0.43,CRN,153,each +cheese,2019,online,11.49,CRN,54,kg +bread,2019,supermarket,0.61,ORO,172,kg +rice,2022,supermarket,2.55,CRN,174,kg +butter,2020,supermarket,1.57,ORO,222,kg +butter,2021,online,1.82,ORO,207,kg +rice,2021,market stall,2.28,CRN,191,kg +cheese,2022,corner shop,12.79,CRN,56,kg +coffee,2021,corner shop,3.20,ORO,63,kg diff --git a/tasks/price-index/price-index-basket-indices-d2-t0076/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d2-t0076/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..0c1a8ddf4a3a0ea2ac3f08e9d4a7fe31822b2f27 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0076/environment/workdir/exchange_rates.csv @@ -0,0 +1,9 @@ +period,currency,crn_per_unit +2019,ORO,4.5561 +2020,ORO,4.6968 +2021,ORO,4.4863 +2022,ORO,4.2111 +2019,ZED,1.9912 +2020,ZED,1.9781 +2021,ZED,2.1717 +2022,ZED,2.1380 diff --git a/tasks/price-index/price-index-basket-indices-d2-t0076/instruction.md b/tasks/price-index/price-index-basket-indices-d2-t0076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6e35c6c04bc86303ee15a579e049c4f2a36d335 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0076/instruction.md @@ -0,0 +1,16 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price per unit and the quantity bought of each item in 4 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +The base year is 2019, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2019"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 4 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d2-t0076/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d2-t0076/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0076/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d2-t0076/tests/verify.py b/tasks/price-index/price-index-basket-indices-d2-t0076/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d2-t0076/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-e0008/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-e0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-e0008/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-e0008/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..0473c203f1206a4cbb58e7341f90b7bb66d154f8 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0008/environment/workdir/basket.csv @@ -0,0 +1,48 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +bread,2015,online,0.08,ORO,100,g,245,kg +apples,2019,corner shop,0.08,ORO,100,g,192,kg +apples,2018,market stall,0.07,ORO,100,g,192,kg +apples,2016,corner shop,0.07,ORO,100,g,191,kg +olive oil,2019,online,3.23,CRN,330,ml,149,litre +apples,2015,online,0.07,ORO,100,g,212,kg +milk,2016,supermarket,0.58,CRN,500,ml,124,litre +sugar,2019,online,3.36,CRN,2,kg,82,kg +potatoes,2017,supermarket,0.79,CRN,500,g,197,kg +coffee,2016,online,1.27,CRN,100,g,68,kg +coffee,2017,market stall,1.40,CRN,100,g,62,kg +bread,2019,corner shop,0.08,ORO,100,g,230,kg +eggs,2018,online,2.28,CRN,6,each,793,each +potatoes,2015,online,0.34,CRN,250,g,218,kg +eggs,2016,supermarket,1.87,CRN,6,each,904,each +milk,2015,corner shop,1.60,CRN,1.5,litre,139,litre +olive oil,2016,corner shop,2.73,CRN,330,ml,195,litre +olive oil,2018,supermarket,3.03,CRN,330,ml,161,litre +tea,2019,corner shop,1.88,ZED,1,kg,154,kg +coffee,2018,online,1.59,CRN,100,g,54,kg +coffee,2015,corner shop,1.30,CRN,100,g,72,kg +bread,2017,market stall,0.08,ORO,100,g,223,kg +tea,2016,supermarket,2.03,ZED,1,kg,157,kg +potatoes,2019,corner shop,1.01,CRN,500,g,178,kg +olive oil,2017,supermarket,2.96,CRN,330,ml,175,litre +eggs,2015,supermarket,1.83,CRN,6,each,942,each +tea,2015,online,0.17,ZED,100,g,176,kg +milk,2019,supermarket,0.58,CRN,500,ml,125,litre +apples,2017,corner shop,0.07,ORO,100,g,202,kg +bread,2016,market stall,0.08,ORO,100,g,238,kg +tea,2018,corner shop,2.12,ZED,1,kg,142,kg +chicken,2018,corner shop,2.13,CRN,250,g,136,kg +chicken,2015,supermarket,7.86,CRN,1,kg,137,kg +olive oil,2015,supermarket,2.56,CRN,330,ml,207,litre +chicken,2016,online,7.93,CRN,1,kg,131,kg +bread,2018,online,0.08,ORO,100,g,211,kg +potatoes,2016,market stall,0.36,CRN,250,g,206,kg +chicken,2017,corner shop,8.69,CRN,1,kg,128,kg +milk,2018,supermarket,0.59,CRN,500,ml,119,litre +tea,2017,supermarket,2.01,ZED,1,kg,153,kg +chicken,2019,market stall,0.96,CRN,100,g,123,kg +eggs,2019,online,4.40,CRN,1,dozen,797,each +sugar,2018,market stall,2.98,CRN,2,kg,84,kg +eggs,2017,market stall,2.11,CRN,6,each,846,each +sugar,2016,corner shop,2.57,CRN,2,kg,96,kg +sugar,2017,corner shop,2.68,CRN,2,kg,96,kg +milk,2017,online,0.56,CRN,500,ml,130,litre diff --git a/tasks/price-index/price-index-basket-indices-d3-e0008/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-e0008/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..fd204aefa2816a707f93d367a3eabb2eb3c5b6b4 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0008/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2015,ORO,3.6169 +2016,ORO,3.9208 +2017,ORO,4.0205 +2018,ORO,4.0190 +2019,ORO,3.7040 +2015,ZED,8.2162 +2016,ZED,7.6621 +2017,ZED,7.4756 +2018,ZED,7.2395 +2019,ZED,7.8825 diff --git a/tasks/price-index/price-index-basket-indices-d3-e0008/instruction.md b/tasks/price-index/price-index-basket-indices-d3-e0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d92d87c28f32cc14b06acba177e52a2896debf7d --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0008/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2015, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2015"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-e0008/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-e0008/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0008/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-e0008/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-e0008/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0008/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-e0020/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-e0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-e0020/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-e0020/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..5ab38e59ff779936af7596d89351d7c08d011f3b --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0020/environment/workdir/basket.csv @@ -0,0 +1,45 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +chicken,2017,corner shop,0.08,ORO,100,g,205,kg +yoghurt,2015,online,1.09,CRN,250,g,180,kg +orange juice,2015,market stall,1.45,CRN,500,ml,54,litre +coffee,2016,supermarket,2.10,ZED,2,kg,35,kg +coffee,2015,online,1.90,ZED,2,kg,34,kg +bread,2019,corner shop,0.30,CRN,100,g,212,kg +pasta,2015,online,0.42,CRN,250,g,67,kg +pasta,2016,supermarket,0.46,CRN,250,g,66,kg +tea,2018,online,42.54,CRN,2,kg,45,kg +butter,2019,corner shop,0.86,ZED,1,kg,184,kg +tea,2017,supermarket,38.52,CRN,2,kg,47,kg +bread,2017,online,0.28,CRN,100,g,230,kg +rice,2017,online,1.08,CRN,500,g,102,kg +chicken,2018,supermarket,0.86,ORO,1,kg,216,kg +bread,2016,supermarket,0.29,CRN,100,g,226,kg +bread,2018,corner shop,0.31,CRN,100,g,220,kg +orange juice,2016,supermarket,1.64,CRN,500,ml,51,litre +pasta,2018,corner shop,0.18,CRN,100,g,71,kg +tea,2015,supermarket,8.83,CRN,500,g,53,kg +butter,2016,supermarket,0.78,ZED,1,kg,188,kg +orange juice,2017,market stall,1.78,CRN,500,ml,48,litre +butter,2017,supermarket,0.80,ZED,1,kg,180,kg +chicken,2016,market stall,0.08,ORO,100,g,214,kg +rice,2018,online,1.20,CRN,500,g,99,kg +potatoes,2016,online,0.35,CRN,250,g,262,kg +potatoes,2019,market stall,0.41,CRN,250,g,237,kg +tea,2016,supermarket,39.88,CRN,2,kg,47,kg +chicken,2019,supermarket,0.23,ORO,250,g,206,kg +pasta,2019,market stall,0.18,CRN,100,g,74,kg +potatoes,2017,corner shop,0.38,CRN,250,g,252,kg +potatoes,2015,corner shop,0.35,CRN,250,g,258,kg +bread,2015,supermarket,0.26,CRN,100,g,238,kg +pasta,2017,market stall,0.45,CRN,250,g,71,kg +orange juice,2019,corner shop,2.01,CRN,500,ml,50,litre +orange juice,2018,online,1.89,CRN,500,ml,49,litre +yoghurt,2018,online,1.11,CRN,250,g,174,kg +tea,2019,online,47.53,CRN,2,kg,40,kg +butter,2015,market stall,0.73,ZED,1,kg,195,kg +yoghurt,2019,supermarket,1.20,CRN,250,g,174,kg +yoghurt,2016,online,1.06,CRN,250,g,179,kg +yoghurt,2017,corner shop,1.15,CRN,250,g,163,kg +rice,2019,online,1.15,CRN,500,g,108,kg +chicken,2015,supermarket,1.67,ORO,2,kg,238,kg +butter,2018,supermarket,0.86,ZED,1,kg,178,kg diff --git a/tasks/price-index/price-index-basket-indices-d3-e0020/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-e0020/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..baa6bb7b230644c596793b34ab0a0084aa698264 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0020/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2015,ORO,6.3162 +2016,ORO,6.7700 +2017,ORO,6.9969 +2018,ORO,6.8589 +2019,ORO,6.3677 +2015,ZED,10.4467 +2016,ZED,9.6268 +2017,ZED,9.5103 +2018,ZED,9.5872 +2019,ZED,9.6211 diff --git a/tasks/price-index/price-index-basket-indices-d3-e0020/instruction.md b/tasks/price-index/price-index-basket-indices-d3-e0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d92d87c28f32cc14b06acba177e52a2896debf7d --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0020/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2015, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2015"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-e0020/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-e0020/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0020/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-e0020/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-e0020/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-e0020/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-t0008/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-t0008/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-t0008/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..ad8d517f113fc3d2c40793bc6735b350cfea3993 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0008/environment/workdir/basket.csv @@ -0,0 +1,46 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +butter,2014,online,0.74,CRN,100,g,173,kg +yoghurt,2011,corner shop,0.05,ORO,100,g,52,kg +butter,2012,market stall,3.40,CRN,500,g,182,kg +tea,2014,online,8.13,CRN,500,g,52,kg +tea,2015,online,8.58,CRN,500,g,49,kg +chicken,2014,online,0.26,ORO,250,g,181,kg +olive oil,2011,market stall,4.53,CRN,75,cl,158,litre +chicken,2011,supermarket,0.22,ORO,250,g,192,kg +butter,2015,market stall,0.74,CRN,100,g,169,kg +potatoes,2015,online,0.06,ZED,500,g,180,kg +olive oil,2014,corner shop,5.92,CRN,75,cl,119,litre +potatoes,2011,corner shop,0.06,ZED,500,g,183,kg +eggs,2014,supermarket,5.71,CRN,1,dozen,555,each +tea,2013,corner shop,7.34,CRN,500,g,57,kg +eggs,2015,supermarket,5.85,CRN,1,dozen,518,each +yoghurt,2012,market stall,0.05,ORO,100,g,50,kg +milk,2013,market stall,1.34,CRN,1,litre,183,litre +apples,2011,corner shop,5.43,CRN,2,kg,183,kg +olive oil,2012,online,4.79,CRN,75,cl,143,litre +chicken,2012,corner shop,0.23,ORO,250,g,183,kg +yoghurt,2015,market stall,0.05,ORO,100,g,42,kg +tea,2012,online,7.45,CRN,500,g,59,kg +potatoes,2013,supermarket,0.06,ZED,500,g,211,kg +potatoes,2012,corner shop,0.07,ZED,500,g,194,kg +apples,2013,supermarket,6.85,CRN,2,kg,153,kg +milk,2014,online,1.38,CRN,1,litre,171,litre +milk,2011,online,1.31,CRN,1,litre,191,litre +bread,2011,supermarket,0.96,CRN,250,g,134,kg +bread,2012,online,0.42,CRN,100,g,131,kg +apples,2014,market stall,7.36,CRN,2,kg,143,kg +bread,2013,supermarket,0.44,CRN,100,g,124,kg +potatoes,2014,market stall,0.06,ZED,500,g,194,kg +olive oil,2013,online,5.44,CRN,75,cl,125,litre +apples,2012,market stall,6.03,CRN,2,kg,167,kg +butter,2013,market stall,0.69,CRN,100,g,190,kg +butter,2011,supermarket,3.23,CRN,500,g,200,kg +yoghurt,2013,corner shop,0.05,ORO,100,g,45,kg +apples,2015,online,7.73,CRN,2,kg,129,kg +milk,2012,supermarket,1.28,CRN,1,litre,198,litre +tea,2011,market stall,7.67,CRN,500,g,56,kg +olive oil,2015,supermarket,2.91,CRN,330,ml,115,litre +chicken,2013,corner shop,0.23,ORO,250,g,193,kg +chicken,2015,online,0.25,ORO,250,g,184,kg +bread,2014,online,4.74,CRN,1,kg,117,kg +bread,2015,online,4.96,CRN,1,kg,112,kg diff --git a/tasks/price-index/price-index-basket-indices-d3-t0008/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-t0008/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..9c5811e1e5e9418af1a9ab0d12008e70f7c078b8 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0008/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2011,ORO,8.6904 +2012,ORO,9.4182 +2013,ORO,9.4260 +2014,ORO,9.1159 +2015,ORO,9.5968 +2011,ZED,10.2882 +2012,ZED,9.8821 +2013,ZED,10.6521 +2014,ZED,11.1668 +2015,ZED,11.9145 diff --git a/tasks/price-index/price-index-basket-indices-d3-t0008/instruction.md b/tasks/price-index/price-index-basket-indices-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63a29071d8914c5f696876f3bd5c80ebbe159323 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0008/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2011, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2011"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-t0008/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-t0008/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0008/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-t0008/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-t0008/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0008/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-t0020/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-t0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-t0020/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-t0020/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..67d5bde9219650b96691b8a95d964dfb61fd801e --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0020/environment/workdir/basket.csv @@ -0,0 +1,45 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +butter,2016,market stall,8.60,CRN,1,kg,103,kg +rice,2016,supermarket,4.75,CRN,2,kg,138,kg +yoghurt,2014,market stall,2.70,ORO,2,kg,230,kg +pasta,2013,market stall,2.00,CRN,1,kg,170,kg +milk,2012,corner shop,0.42,CRN,500,ml,165,litre +yoghurt,2012,corner shop,2.55,ORO,2,kg,222,kg +cheese,2015,online,1.16,CRN,100,g,211,kg +milk,2015,corner shop,0.48,CRN,500,ml,137,litre +chicken,2012,corner shop,6.96,CRN,1,kg,25,kg +milk,2013,market stall,0.47,CRN,500,ml,152,litre +rice,2014,market stall,1.03,CRN,500,g,152,kg +pasta,2014,corner shop,1.95,CRN,1,kg,165,kg +chicken,2014,corner shop,8.09,CRN,1,kg,21,kg +yoghurt,2016,online,2.84,ORO,2,kg,206,kg +pasta,2016,market stall,2.31,CRN,1,kg,158,kg +yoghurt,2015,corner shop,2.70,ORO,2,kg,213,kg +butter,2014,market stall,2.20,CRN,250,g,98,kg +chicken,2013,corner shop,7.89,CRN,1,kg,22,kg +chicken,2015,supermarket,8.60,CRN,1,kg,21,kg +yoghurt,2013,corner shop,2.71,ORO,2,kg,233,kg +milk,2014,market stall,0.48,CRN,500,ml,146,litre +sugar,2012,supermarket,2.49,CRN,2,kg,231,kg +pasta,2015,supermarket,2.15,CRN,1,kg,157,kg +sugar,2013,online,2.43,CRN,2,kg,247,kg +bread,2012,online,0.11,ORO,100,g,165,kg +sugar,2016,corner shop,0.69,CRN,500,g,221,kg +cheese,2012,corner shop,1.09,CRN,100,g,230,kg +rice,2013,online,1.07,CRN,500,g,139,kg +bread,2016,corner shop,0.14,ORO,100,g,161,kg +cheese,2013,corner shop,21.13,CRN,2,kg,225,kg +bread,2013,supermarket,0.14,ORO,100,g,161,kg +sugar,2014,online,1.22,CRN,1,kg,232,kg +cheese,2014,supermarket,22.99,CRN,2,kg,220,kg +tea,2012,corner shop,2.90,ORO,500,g,38,kg +cheese,2016,supermarket,1.15,CRN,100,g,211,kg +rice,2012,corner shop,0.97,CRN,500,g,153,kg +bread,2014,corner shop,0.14,ORO,100,g,157,kg +butter,2015,market stall,2.23,CRN,250,g,100,kg +tea,2013,market stall,3.33,ORO,500,g,38,kg +rice,2015,corner shop,4.36,CRN,2,kg,155,kg +chicken,2016,online,9.67,CRN,1,kg,18,kg +milk,2016,corner shop,0.53,CRN,500,ml,136,litre +pasta,2012,supermarket,1.87,CRN,1,kg,183,kg +bread,2015,supermarket,0.13,ORO,100,g,157,kg diff --git a/tasks/price-index/price-index-basket-indices-d3-t0020/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-t0020/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..438b9b45ffbf3a3b55b8dc0b3c0e6f18f60d6d2f --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0020/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2012,ORO,2.6408 +2013,ORO,2.4537 +2014,ORO,2.4622 +2015,ORO,2.5816 +2016,ORO,2.5313 +2012,ZED,4.7440 +2013,ZED,4.9998 +2014,ZED,4.6794 +2015,ZED,4.3946 +2016,ZED,4.6304 diff --git a/tasks/price-index/price-index-basket-indices-d3-t0020/instruction.md b/tasks/price-index/price-index-basket-indices-d3-t0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..45847a0788565ad029b19032b15aa6426326da90 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0020/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2012, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2012"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-t0020/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-t0020/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0020/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-t0020/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-t0020/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0020/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-t0032/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-t0032/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0032/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-t0032/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-t0032/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..f55d3af66deb62074b8a3f9431f714927e5a77ad --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0032/environment/workdir/basket.csv @@ -0,0 +1,45 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +cheese,2017,supermarket,9.49,CRN,1,kg,156,kg +apples,2017,online,0.74,ZED,500,g,103,kg +olive oil,2016,supermarket,11.70,CRN,1,litre,133,litre +butter,2014,corner shop,1.99,CRN,250,g,226,kg +orange juice,2016,supermarket,2.09,CRN,1,litre,236,litre +sugar,2017,supermarket,3.66,CRN,2,kg,101,kg +cheese,2013,supermarket,3.95,CRN,500,g,180,kg +yoghurt,2015,supermarket,0.73,ZED,500,g,81,kg +milk,2015,corner shop,0.19,ZED,330,ml,224,litre +milk,2014,corner shop,0.19,ZED,330,ml,222,litre +milk,2016,supermarket,0.19,ZED,330,ml,218,litre +bread,2013,supermarket,3.73,CRN,1,kg,210,kg +cheese,2015,online,4.30,CRN,500,g,167,kg +butter,2013,corner shop,1.81,CRN,250,g,229,kg +potatoes,2015,supermarket,0.32,CRN,250,g,61,kg +yoghurt,2013,online,0.82,ZED,500,g,78,kg +potatoes,2016,online,2.62,CRN,2,kg,62,kg +potatoes,2017,online,2.96,CRN,2,kg,58,kg +potatoes,2014,online,0.29,CRN,250,g,67,kg +yoghurt,2016,corner shop,0.79,ZED,500,g,74,kg +sugar,2014,corner shop,3.06,CRN,2,kg,122,kg +olive oil,2013,supermarket,9.14,CRN,1,litre,144,litre +orange juice,2017,supermarket,2.15,CRN,1,litre,223,litre +milk,2017,online,0.17,ZED,330,ml,205,litre +olive oil,2017,corner shop,13.25,CRN,1,litre,120,litre +sugar,2016,corner shop,3.39,CRN,2,kg,105,kg +sugar,2015,supermarket,3.21,CRN,2,kg,112,kg +yoghurt,2014,online,0.78,ZED,500,g,79,kg +milk,2013,online,0.20,ZED,330,ml,230,litre +apples,2015,online,0.72,ZED,500,g,108,kg +apples,2014,online,0.74,ZED,500,g,106,kg +bread,2014,supermarket,4.06,CRN,1,kg,205,kg +apples,2013,corner shop,0.15,ZED,100,g,116,kg +bread,2015,online,4.52,CRN,1,kg,203,kg +bread,2017,online,11.30,CRN,2,kg,161,kg +apples,2016,supermarket,0.77,ZED,500,g,98,kg +orange juice,2015,market stall,2.15,CRN,1,litre,248,litre +olive oil,2015,corner shop,11.52,CRN,1,litre,127,litre +sugar,2013,corner shop,2.92,CRN,2,kg,122,kg +cheese,2016,supermarket,4.51,CRN,500,g,171,kg +bread,2016,market stall,10.22,CRN,2,kg,183,kg +yoghurt,2017,market stall,0.82,ZED,500,g,70,kg +potatoes,2013,corner shop,1.06,CRN,1,kg,71,kg +cheese,2014,corner shop,4.15,CRN,500,g,169,kg diff --git a/tasks/price-index/price-index-basket-indices-d3-t0032/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-t0032/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..73192f1e298c3dc342a84b019ab4bc68d0ccec7d --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0032/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2013,ORO,8.3836 +2014,ORO,9.0017 +2015,ORO,8.9462 +2016,ORO,9.8391 +2017,ORO,9.8301 +2013,ZED,2.0931 +2014,ZED,2.2513 +2015,ZED,2.3610 +2016,ZED,2.3386 +2017,ZED,2.4724 diff --git a/tasks/price-index/price-index-basket-indices-d3-t0032/instruction.md b/tasks/price-index/price-index-basket-indices-d3-t0032/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..334bca1c7d5958e4b18ab7e1b291cad6f92986fd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0032/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2013, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2013"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-t0032/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-t0032/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0032/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-t0032/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-t0032/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0032/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-t0044/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-t0044/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0044/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-t0044/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-t0044/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..b8dddd0c538f60762184d7cf8b10419eb7fface5 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0044/environment/workdir/basket.csv @@ -0,0 +1,47 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +yoghurt,2024,corner shop,10.18,CRN,2,kg,154,kg +rice,2023,market stall,2.24,CRN,1,kg,247,kg +olive oil,2024,corner shop,3.26,CRN,330,ml,132,litre +pasta,2022,corner shop,0.40,CRN,250,g,40,kg +pasta,2021,online,0.40,CRN,250,g,43,kg +olive oil,2021,online,3.02,CRN,330,ml,145,litre +yoghurt,2020,online,2.21,CRN,500,g,174,kg +chicken,2021,market stall,7.45,ZED,2,kg,125,kg +chicken,2020,corner shop,7.25,ZED,2,kg,132,kg +sugar,2021,corner shop,0.32,CRN,250,g,26,kg +yoghurt,2022,market stall,10.41,CRN,2,kg,161,kg +cheese,2021,online,2.35,CRN,250,g,44,kg +apples,2022,corner shop,0.34,ORO,500,g,199,kg +pasta,2023,corner shop,0.43,CRN,250,g,36,kg +chicken,2023,online,0.91,ZED,250,g,111,kg +potatoes,2023,market stall,3.03,CRN,2,kg,48,kg +potatoes,2024,online,3.04,CRN,2,kg,49,kg +yoghurt,2021,corner shop,2.29,CRN,500,g,177,kg +apples,2023,corner shop,0.06,ORO,100,g,216,kg +chicken,2024,online,0.98,ZED,250,g,104,kg +cheese,2023,corner shop,2.82,CRN,250,g,39,kg +rice,2021,supermarket,2.38,CRN,1,kg,243,kg +potatoes,2020,supermarket,2.26,CRN,2,kg,58,kg +cheese,2020,market stall,2.25,CRN,250,g,43,kg +apples,2020,corner shop,0.35,ORO,500,g,182,kg +sugar,2020,online,2.46,CRN,2,kg,25,kg +butter,2022,corner shop,1.36,ZED,250,g,88,kg +cheese,2022,online,2.54,CRN,250,g,41,kg +rice,2020,online,2.45,CRN,1,kg,229,kg +potatoes,2021,corner shop,2.57,CRN,2,kg,50,kg +potatoes,2022,market stall,2.84,CRN,2,kg,48,kg +pasta,2024,market stall,0.42,CRN,250,g,35,kg +chicken,2022,supermarket,0.88,ZED,250,g,126,kg +pasta,2020,corner shop,0.41,CRN,250,g,45,kg +butter,2024,market stall,1.42,ZED,250,g,86,kg +apples,2021,online,0.35,ORO,500,g,192,kg +olive oil,2022,online,2.97,CRN,330,ml,141,litre +rice,2022,corner shop,2.31,CRN,1,kg,254,kg +rice,2024,supermarket,2.55,CRN,1,kg,225,kg +apples,2024,online,0.07,ORO,100,g,196,kg +olive oil,2023,online,2.95,CRN,330,ml,140,litre +sugar,2022,online,0.32,CRN,250,g,25,kg +butter,2023,market stall,1.27,ZED,250,g,94,kg +butter,2020,online,1.42,ZED,250,g,81,kg +yoghurt,2023,supermarket,10.36,CRN,2,kg,155,kg +cheese,2024,market stall,2.82,CRN,250,g,41,kg diff --git a/tasks/price-index/price-index-basket-indices-d3-t0044/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-t0044/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..1ec4ba9a2a005ec8fa686fff6b91bbac91a05f25 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0044/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2020,ORO,4.3870 +2021,ORO,4.4223 +2022,ORO,4.3998 +2023,ORO,4.7773 +2024,ORO,4.5007 +2020,ZED,1.6196 +2021,ZED,1.7290 +2022,ZED,1.8148 +2023,ZED,1.9026 +2024,ZED,1.8338 diff --git a/tasks/price-index/price-index-basket-indices-d3-t0044/instruction.md b/tasks/price-index/price-index-basket-indices-d3-t0044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c648db5537b669a338ca7a5964b0ecb9b647109 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0044/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2020, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2020"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-t0044/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-t0044/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0044/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-t0044/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-t0044/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0044/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-t0056/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-t0056/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0056/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-t0056/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-t0056/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..54df422f08393b5e7b9466906fdc906e3b22fd46 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0056/environment/workdir/basket.csv @@ -0,0 +1,44 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +pasta,2015,market stall,0.91,CRN,500,g,279,kg +olive oil,2012,corner shop,0.74,ZED,330,ml,140,litre +pasta,2012,corner shop,0.94,CRN,500,g,237,kg +milk,2015,market stall,1.64,CRN,1,litre,191,litre +olive oil,2013,online,0.73,ZED,330,ml,142,litre +olive oil,2016,online,0.77,ZED,330,ml,149,litre +tea,2013,online,1.20,CRN,100,g,55,kg +pasta,2013,online,0.90,CRN,500,g,257,kg +bread,2013,corner shop,0.28,ZED,250,g,230,kg +orange juice,2014,supermarket,3.66,CRN,1,litre,180,litre +orange juice,2016,corner shop,3.41,CRN,75,cl,151,litre +orange juice,2015,supermarket,4.04,CRN,1,litre,169,litre +rice,2013,supermarket,0.73,CRN,250,g,22,kg +rice,2015,corner shop,1.62,CRN,500,g,21,kg +coffee,2013,online,6.50,ZED,2,kg,76,kg +coffee,2015,market stall,7.97,ZED,2,kg,67,kg +coffee,2014,online,7.33,ZED,2,kg,76,kg +bread,2014,market stall,0.32,ZED,250,g,197,kg +rice,2012,online,0.71,CRN,250,g,23,kg +milk,2014,market stall,1.54,CRN,1,litre,204,litre +olive oil,2015,corner shop,0.70,ZED,330,ml,145,litre +chicken,2015,online,12.04,CRN,1,kg,94,kg +tea,2015,corner shop,1.38,CRN,100,g,55,kg +rice,2016,market stall,1.77,CRN,500,g,19,kg +milk,2012,market stall,1.39,CRN,1,litre,225,litre +coffee,2016,corner shop,9.49,ZED,2,kg,65,kg +milk,2016,supermarket,1.71,CRN,1,litre,187,litre +tea,2014,corner shop,1.34,CRN,100,g,53,kg +bread,2016,supermarket,0.16,ZED,100,g,175,kg +milk,2013,corner shop,1.37,CRN,1,litre,221,litre +tea,2016,corner shop,1.37,CRN,100,g,52,kg +olive oil,2014,supermarket,0.73,ZED,330,ml,143,litre +coffee,2012,online,0.72,ZED,250,g,88,kg +rice,2014,market stall,1.66,CRN,500,g,21,kg +orange juice,2013,supermarket,3.23,CRN,1,litre,205,litre +apples,2012,corner shop,0.24,CRN,100,g,69,kg +bread,2012,supermarket,0.27,ZED,250,g,232,kg +apples,2013,supermarket,0.27,CRN,100,g,67,kg +pasta,2014,supermarket,0.91,CRN,500,g,272,kg +orange juice,2012,market stall,2.94,CRN,1,litre,224,litre +pasta,2016,online,1.01,CRN,500,g,267,kg +tea,2012,corner shop,1.25,CRN,100,g,58,kg +chicken,2016,corner shop,12.67,CRN,1,kg,89,kg diff --git a/tasks/price-index/price-index-basket-indices-d3-t0056/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-t0056/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..f5681048143f5b07b7f5cc0781cd204e42d00554 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0056/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2012,ORO,5.3334 +2013,ORO,5.7756 +2014,ORO,5.8532 +2015,ORO,5.5313 +2016,ORO,5.1334 +2012,ZED,3.6101 +2013,ZED,3.6596 +2014,ZED,3.5784 +2015,ZED,3.6186 +2016,ZED,3.3431 diff --git a/tasks/price-index/price-index-basket-indices-d3-t0056/instruction.md b/tasks/price-index/price-index-basket-indices-d3-t0056/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..45847a0788565ad029b19032b15aa6426326da90 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0056/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2012, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2012"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-t0056/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-t0056/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0056/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-t0056/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-t0056/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0056/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-t0068/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-t0068/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0068/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-t0068/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-t0068/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..bae81e2d8a576637bad631a3d77f4ef7045173e5 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0068/environment/workdir/basket.csv @@ -0,0 +1,45 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +cheese,2020,online,0.24,ORO,250,g,194,kg +coffee,2023,market stall,9.07,CRN,500,g,209,kg +potatoes,2020,online,0.31,CRN,250,g,67,kg +rice,2022,corner shop,0.32,CRN,100,g,251,kg +orange juice,2020,corner shop,1.80,CRN,75,cl,202,litre +chicken,2023,supermarket,20.23,CRN,2,kg,52,kg +rice,2019,market stall,0.69,CRN,250,g,241,kg +bread,2023,market stall,0.41,ORO,1,kg,115,kg +butter,2021,corner shop,1.02,ZED,250,g,246,kg +coffee,2020,online,7.42,CRN,500,g,227,kg +rice,2023,corner shop,1.80,CRN,500,g,229,kg +butter,2019,supermarket,0.37,ZED,100,g,256,kg +cheese,2019,supermarket,1.69,ORO,2,kg,210,kg +eggs,2019,market stall,1.34,CRN,6,each,1506,each +cheese,2023,online,0.27,ORO,250,g,174,kg +eggs,2022,supermarket,1.50,CRN,6,each,1668,each +rice,2021,online,0.31,CRN,100,g,247,kg +butter,2020,online,0.99,ZED,250,g,256,kg +chicken,2021,market stall,20.32,CRN,2,kg,53,kg +chicken,2022,corner shop,21.03,CRN,2,kg,53,kg +orange juice,2019,supermarket,3.64,CRN,1.5,litre,194,litre +butter,2023,online,1.30,ZED,250,g,213,kg +potatoes,2021,corner shop,0.64,CRN,500,g,70,kg +coffee,2019,supermarket,6.84,CRN,500,g,249,kg +eggs,2021,online,1.50,CRN,6,each,1583,each +eggs,2023,market stall,1.50,CRN,6,each,1768,each +bread,2022,online,0.34,ORO,1,kg,130,kg +chicken,2019,market stall,17.85,CRN,2,kg,60,kg +cheese,2022,market stall,0.23,ORO,250,g,179,kg +yoghurt,2020,corner shop,9.72,CRN,2,kg,86,kg +butter,2022,supermarket,1.09,ZED,250,g,233,kg +yoghurt,2019,online,8.77,CRN,2,kg,96,kg +eggs,2020,online,1.34,CRN,6,each,1599,each +potatoes,2023,corner shop,0.72,CRN,500,g,65,kg +orange juice,2023,online,4.00,CRN,1.5,litre,186,litre +coffee,2021,market stall,7.94,CRN,500,g,222,kg +coffee,2022,online,8.83,CRN,500,g,211,kg +chicken,2020,online,19.44,CRN,2,kg,56,kg +cheese,2021,corner shop,0.22,ORO,250,g,187,kg +orange juice,2022,online,2.07,CRN,75,cl,183,litre +yoghurt,2021,online,10.91,CRN,2,kg,85,kg +potatoes,2019,supermarket,0.29,CRN,250,g,67,kg +orange juice,2021,corner shop,1.97,CRN,75,cl,181,litre +rice,2020,online,0.29,CRN,100,g,247,kg diff --git a/tasks/price-index/price-index-basket-indices-d3-t0068/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-t0068/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..f055afe244a6abb601ff5c6b0523ff59b335475e --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0068/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2019,ORO,8.7376 +2020,ORO,8.6876 +2021,ORO,9.2837 +2022,ORO,8.6349 +2023,ORO,8.0123 +2019,ZED,2.0571 +2020,ZED,1.9223 +2021,ZED,1.8489 +2022,ZED,1.9383 +2023,ZED,1.8356 diff --git a/tasks/price-index/price-index-basket-indices-d3-t0068/instruction.md b/tasks/price-index/price-index-basket-indices-d3-t0068/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf2d64469ca5d2552181f330db2734e6c653fe56 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0068/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2019, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2019"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-t0068/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-t0068/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0068/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-t0068/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-t0068/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0068/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-basket-indices-d3-t0080/environment/Dockerfile b/tasks/price-index/price-index-basket-indices-d3-t0080/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0080/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-basket-indices-d3-t0080/environment/workdir/basket.csv b/tasks/price-index/price-index-basket-indices-d3-t0080/environment/workdir/basket.csv new file mode 100644 index 0000000000000000000000000000000000000000..b8729d2d57b3dd59f330658e61bf003ec769af41 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0080/environment/workdir/basket.csv @@ -0,0 +1,46 @@ +item,period,outlet,price,currency,pack_size,pack_unit,quantity,quantity_unit +olive oil,2019,supermarket,2.07,ORO,1,litre,84,litre +eggs,2019,market stall,1.39,CRN,6,each,453,each +olive oil,2018,market stall,2.16,ORO,1,litre,84,litre +tea,2018,supermarket,11.60,CRN,1,kg,24,kg +cheese,2022,market stall,9.36,CRN,1,kg,29,kg +apples,2021,corner shop,1.76,CRN,500,g,238,kg +cheese,2020,market stall,8.47,CRN,1,kg,30,kg +chicken,2021,corner shop,19.68,CRN,2,kg,210,kg +coffee,2021,online,6.60,CRN,500,g,59,kg +olive oil,2021,corner shop,0.91,ORO,330,ml,69,litre +chicken,2020,online,18.43,CRN,2,kg,207,kg +eggs,2022,corner shop,3.30,CRN,1,dozen,377,each +chicken,2019,market stall,18.69,CRN,2,kg,205,kg +tea,2021,market stall,12.18,CRN,1,kg,24,kg +pasta,2021,market stall,0.05,ORO,100,g,59,kg +coffee,2022,online,7.12,CRN,500,g,55,kg +orange juice,2022,corner shop,1.40,CRN,500,ml,164,litre +olive oil,2020,supermarket,2.25,ORO,1,litre,74,litre +apples,2018,supermarket,1.49,CRN,500,g,251,kg +apples,2022,online,1.73,CRN,500,g,245,kg +orange juice,2021,supermarket,1.31,CRN,500,ml,184,litre +apples,2019,corner shop,1.50,CRN,500,g,251,kg +tea,2019,online,11.47,CRN,1,kg,26,kg +coffee,2018,market stall,6.02,CRN,500,g,56,kg +pasta,2018,online,0.17,ORO,500,g,61,kg +potatoes,2020,market stall,0.09,ZED,250,g,228,kg +chicken,2018,supermarket,17.58,CRN,2,kg,207,kg +eggs,2018,online,1.39,CRN,6,each,438,each +eggs,2021,supermarket,3.15,CRN,1,dozen,372,each +chicken,2022,online,5.11,CRN,500,g,195,kg +apples,2020,corner shop,1.63,CRN,500,g,248,kg +pasta,2022,corner shop,0.05,ORO,100,g,61,kg +tea,2020,corner shop,11.41,CRN,1,kg,26,kg +cheese,2019,corner shop,8.17,CRN,1,kg,30,kg +pasta,2019,online,0.05,ORO,100,g,59,kg +coffee,2020,online,6.59,CRN,500,g,56,kg +coffee,2019,online,6.31,CRN,500,g,55,kg +olive oil,2022,corner shop,0.92,ORO,330,ml,68,litre +cheese,2018,market stall,7.45,CRN,1,kg,34,kg +potatoes,2019,corner shop,0.07,ZED,250,g,262,kg +pasta,2020,market stall,0.05,ORO,100,g,58,kg +potatoes,2018,corner shop,0.06,ZED,250,g,258,kg +eggs,2020,market stall,2.92,CRN,1,dozen,420,each +tea,2022,supermarket,13.27,CRN,1,kg,23,kg +cheese,2021,corner shop,8.81,CRN,1,kg,30,kg diff --git a/tasks/price-index/price-index-basket-indices-d3-t0080/environment/workdir/exchange_rates.csv b/tasks/price-index/price-index-basket-indices-d3-t0080/environment/workdir/exchange_rates.csv new file mode 100644 index 0000000000000000000000000000000000000000..b3b02dccc94fd3120907e19aab50d4a5396ee3fd --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0080/environment/workdir/exchange_rates.csv @@ -0,0 +1,11 @@ +period,currency,crn_per_unit +2018,ORO,4.3759 +2019,ORO,4.4845 +2020,ORO,4.5801 +2021,ORO,4.2140 +2022,ORO,4.5632 +2018,ZED,4.7727 +2019,ZED,4.5993 +2020,ZED,4.2335 +2021,ZED,4.1724 +2022,ZED,4.1355 diff --git a/tasks/price-index/price-index-basket-indices-d3-t0080/instruction.md b/tasks/price-index/price-index-basket-indices-d3-t0080/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..10e324f82360cefc64532785bcc0ad24ab6a1bbe --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0080/instruction.md @@ -0,0 +1,22 @@ +# Price indices for a household basket + +`basket.csv` gives, for a reference household, the price and the quantity bought of each item in up to 5 years, in no particular order. Some items are imported and priced in a foreign currency. Convert every price to crowns (CRN) with the rate for the same period in `exchange_rates.csv` (crowns per one unit of the foreign currency). Prices already in CRN need no conversion. + +`price` is the price of one pack of `pack_size` `pack_unit`, and the pack on sale can change from one year to the next. `quantity` is the amount bought, in `quantity_unit` (kg, litre or each). Before anything else, turn every price into a price per `quantity_unit`: 1 kg = 1000 g; 1 litre = 100 cl = 1000 ml; 1 dozen = 12 items (`each`). + +Some items were not on sale, or not priced, in every year. Use only the items that have a row in all 5 years, and leave the others out of every calculation, in every year. + +The base year is 2018, the earliest year. With p for price, q for quantity, 0 for the base year and t for the year in question, and sums running over the items: + +- Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0) +- Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t) +- Fisher index = square root of (Laspeyres x Paasche) + +Write `answer.json` in this folder, a JSON object with: + +- `basket_cost`: object keyed by year (as a string, for example `"2018"`): what the household spent that year, the sum of price x quantity in crowns, 2 decimals. One entry for each of the 5 years. +- `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals. +- `excluded_items`: list of the items left out because they lack a row in some year (any order). +- `fisher_change_percent`: object keyed by year, for every year after the base year: the percentage change of the Fisher index from the year before (the base-year index is 100), 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-basket-indices-d3-t0080/solution/oracle.py b/tasks/price-index/price-index-basket-indices-d3-t0080/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0080/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-basket-indices-d3-t0080/tests/verify.py b/tasks/price-index/price-index-basket-indices-d3-t0080/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-basket-indices-d3-t0080/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-e0001/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-e0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-e0001/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-e0001/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..563d0307cc38bfd6d4668c6a74765fd8f19f9436 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0001/environment/workdir/households.csv @@ -0,0 +1,31 @@ +household_id,region,disposable_income +H167,west,17358 +H028,west,37120 +H275,south,24922 +H342,west,14115 +H151,north,17762 +H191,south,25515 +H373,east,17232 +H218,south,5597 +H056,south,19199 +H050,north,20741 +H149,west,17111 +H208,west,45097 +H392,north,36219 +H031,south,22498 +H070,south,37583 +H048,west,25112 +H002,north,23381 +H084,north,64350 +H394,south,47311 +H176,west,24952 +H371,east,24354 +H387,south,20789 +H321,north,67537 +H075,west,15022 +H128,north,26230 +H080,east,8174 +H024,east,31846 +H269,south,11304 +H152,west,30773 +H252,south,38047 diff --git a/tasks/price-index/price-index-income-distribution-d1-e0001/instruction.md b/tasks/price-index/price-index-income-distribution-d1-e0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f94207eff4f7458d6e38b544a719dc681638c91e --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0001/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 30 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-e0001/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-e0001/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0001/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-e0001/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-e0001/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0001/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-e0013/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-e0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-e0013/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-e0013/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..23c02011cc84c446c7d0f6647c3cb89d4ce2a6d3 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0013/environment/workdir/households.csv @@ -0,0 +1,21 @@ +household_id,region,disposable_income +H325,north,59199 +H007,east,74398 +H369,east,40412 +H217,east,31495 +H302,north,41235 +H060,south,70507 +H018,north,54462 +H366,west,27307 +H071,south,83122 +H317,east,45579 +H262,west,27743 +H360,north,87211 +H398,north,47551 +H306,west,31905 +H161,south,37999 +H308,north,19473 +H059,west,43917 +H281,east,47818 +H112,east,30551 +H339,south,32658 diff --git a/tasks/price-index/price-index-income-distribution-d1-e0013/instruction.md b/tasks/price-index/price-index-income-distribution-d1-e0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5cc11294cda6eb0d81bc7c0c6fc4fd1c76694d37 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0013/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 20 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-e0013/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-e0013/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0013/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-e0013/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-e0013/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-e0013/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-t0001/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-t0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-t0001/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-t0001/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..ffdae3f59b00cb9d0de74335766ff1ca800bac2c --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0001/environment/workdir/households.csv @@ -0,0 +1,31 @@ +household_id,region,disposable_income +H266,west,19587 +H340,south,25471 +H310,east,51838 +H240,east,47922 +H102,west,51375 +H138,north,35650 +H296,north,51251 +H376,north,35967 +H306,east,33758 +H059,north,59499 +H386,south,22449 +H081,south,27472 +H241,south,71923 +H132,west,45086 +H346,north,48503 +H167,west,38653 +H302,east,22521 +H195,north,36812 +H075,south,26076 +H338,north,50676 +H083,north,36628 +H007,north,17807 +H161,east,9148 +H215,east,69519 +H259,north,47829 +H264,west,55300 +H001,south,26183 +H383,south,14673 +H105,south,33315 +H272,west,33801 diff --git a/tasks/price-index/price-index-income-distribution-d1-t0001/instruction.md b/tasks/price-index/price-index-income-distribution-d1-t0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f94207eff4f7458d6e38b544a719dc681638c91e --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0001/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 30 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-t0001/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-t0001/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0001/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-t0001/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-t0001/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0001/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-t0013/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-t0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-t0013/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-t0013/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..3154fae871e020f12d0f00a1147da7c9eee1c4ce --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0013/environment/workdir/households.csv @@ -0,0 +1,21 @@ +household_id,region,disposable_income +H272,west,29285 +H383,east,34875 +H332,south,15603 +H351,north,20270 +H134,north,5442 +H228,south,31672 +H166,north,14290 +H163,east,19779 +H214,north,19198 +H101,south,34742 +H116,north,57533 +H392,west,15600 +H178,east,13184 +H165,east,17970 +H375,east,25554 +H086,south,14877 +H202,east,18836 +H128,west,29397 +H221,west,17239 +H250,north,10622 diff --git a/tasks/price-index/price-index-income-distribution-d1-t0013/instruction.md b/tasks/price-index/price-index-income-distribution-d1-t0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5cc11294cda6eb0d81bc7c0c6fc4fd1c76694d37 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0013/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 20 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-t0013/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-t0013/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0013/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-t0013/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-t0013/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0013/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-t0025/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-t0025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0025/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-t0025/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-t0025/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..866f49a49bc7cac5c3505964b6f0183068e1618d --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0025/environment/workdir/households.csv @@ -0,0 +1,21 @@ +household_id,region,disposable_income +H012,east,38362 +H127,west,73872 +H134,north,75513 +H023,east,33560 +H093,south,46916 +H262,north,29425 +H034,south,24026 +H307,north,40893 +H140,east,36923 +H126,south,32226 +H084,east,25908 +H099,west,17504 +H386,west,16729 +H220,north,65240 +H160,west,45659 +H397,east,37718 +H067,north,38506 +H354,south,41671 +H135,south,19142 +H226,north,40776 diff --git a/tasks/price-index/price-index-income-distribution-d1-t0025/instruction.md b/tasks/price-index/price-index-income-distribution-d1-t0025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5cc11294cda6eb0d81bc7c0c6fc4fd1c76694d37 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0025/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 20 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-t0025/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-t0025/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0025/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-t0025/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-t0025/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0025/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-t0037/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-t0037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0037/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-t0037/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-t0037/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..600f9b77e4b042b775c6fe5c941916c46ecc39e4 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0037/environment/workdir/households.csv @@ -0,0 +1,26 @@ +household_id,region,disposable_income +H039,south,70399 +H378,north,46774 +H149,east,18972 +H343,west,28895 +H212,west,33848 +H093,north,19414 +H057,south,78135 +H321,north,15839 +H111,west,36746 +H067,north,14641 +H013,west,17337 +H128,north,6278 +H244,east,22926 +H107,south,41646 +H178,south,35128 +H054,west,19067 +H369,east,16178 +H341,west,12202 +H062,west,10167 +H310,south,22875 +H197,west,17905 +H399,north,11132 +H374,east,21160 +H109,west,41316 +H299,south,28194 diff --git a/tasks/price-index/price-index-income-distribution-d1-t0037/instruction.md b/tasks/price-index/price-index-income-distribution-d1-t0037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8724ca03f2e95b42fc269955cf3700f1e8c12fcf --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0037/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 25 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-t0037/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-t0037/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0037/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-t0037/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-t0037/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0037/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-t0049/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-t0049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0049/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-t0049/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-t0049/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..88ed7ac0c66a0a22aacf5c900260b783fa3dad07 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0049/environment/workdir/households.csv @@ -0,0 +1,26 @@ +household_id,region,disposable_income +H122,south,28450 +H371,east,37074 +H321,east,12642 +H186,west,33326 +H234,south,28468 +H372,north,27617 +H301,west,62648 +H353,west,10646 +H257,north,46542 +H262,east,23486 +H196,south,54359 +H028,east,59887 +H104,east,143165 +H165,west,93065 +H139,west,56116 +H041,west,44474 +H072,south,73347 +H125,west,34965 +H074,north,21208 +H280,east,42736 +H180,south,67188 +H068,east,71196 +H264,south,20621 +H078,east,15573 +H267,west,25615 diff --git a/tasks/price-index/price-index-income-distribution-d1-t0049/instruction.md b/tasks/price-index/price-index-income-distribution-d1-t0049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8724ca03f2e95b42fc269955cf3700f1e8c12fcf --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0049/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 25 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-t0049/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-t0049/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0049/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-t0049/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-t0049/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0049/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-t0061/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-t0061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0061/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-t0061/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-t0061/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..8f455d7c99622c056fd608135b546bfab849f5e6 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0061/environment/workdir/households.csv @@ -0,0 +1,26 @@ +household_id,region,disposable_income +H239,east,22338 +H174,east,25641 +H051,south,25058 +H331,east,31441 +H251,east,29185 +H391,north,18158 +H146,north,26825 +H103,south,16740 +H006,east,25935 +H170,south,28336 +H048,east,14694 +H141,east,18381 +H364,north,70248 +H241,south,55599 +H110,south,16901 +H017,north,32977 +H336,east,47357 +H199,east,35431 +H309,east,44732 +H373,south,23777 +H010,east,24134 +H093,west,20135 +H388,north,28044 +H348,south,39266 +H324,west,46962 diff --git a/tasks/price-index/price-index-income-distribution-d1-t0061/instruction.md b/tasks/price-index/price-index-income-distribution-d1-t0061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8724ca03f2e95b42fc269955cf3700f1e8c12fcf --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0061/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 25 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-t0061/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-t0061/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0061/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-t0061/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-t0061/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0061/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d1-t0073/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d1-t0073/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0073/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d1-t0073/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d1-t0073/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..cb3a45b0200f4f7fafe84ac3d018f313cd5dba40 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0073/environment/workdir/households.csv @@ -0,0 +1,21 @@ +household_id,region,disposable_income +H093,west,57730 +H222,west,47899 +H132,north,55607 +H037,east,57182 +H102,east,29313 +H322,west,54824 +H158,north,23875 +H278,east,23505 +H328,east,30695 +H293,west,49599 +H005,west,33896 +H189,east,28355 +H142,west,15974 +H269,east,81058 +H241,west,83569 +H168,north,20088 +H076,west,10996 +H075,south,268917 +H198,east,31157 +H035,east,91803 diff --git a/tasks/price-index/price-index-income-distribution-d1-t0073/instruction.md b/tasks/price-index/price-index-income-distribution-d1-t0073/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5cc11294cda6eb0d81bc7c0c6fc4fd1c76694d37 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0073/instruction.md @@ -0,0 +1,21 @@ +# Income distribution from a household survey + +`households.csv` gives the annual disposable income of 20 households from a survey. Each household is one observation. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d1-t0073/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d1-t0073/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0073/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d1-t0073/tests/verify.py b/tasks/price-index/price-index-income-distribution-d1-t0073/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d1-t0073/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-e0005/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-e0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-e0005/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-e0005/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..29c660a5f606ef53d9bc2e91205e65f111a0b497 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0005/environment/workdir/households.csv @@ -0,0 +1,41 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H185,east,tenant,32038,13731,5766,10418 +H028,north,tenant,47977,0,47145,10501 +H069,east,owner,71278,0,6917,20374 +H175,west,tenant,24038,10302,1445,7100 +H161,north,tenant,26983,0,8796,5299 +H293,north,tenant,17926,7683,3357,5313 +H325,west,owner,0,106219,0,24773 +H258,north,owner,7133,0,11966,1866 +H349,north,owner,31525,0,0,6394 +H047,west,tenant,21944,9405,14131,7831 +H085,north,tenant,11733,0,11810,2312 +H169,north,owner,100256,0,0,32757 +H260,north,tenant,51011,0,29862,10624 +H183,south,tenant,0,79369,11030,24460 +H309,east,tenant,107392,0,13269,30076 +H280,north,tenant,37938,16259,6731,18375 +H067,north,owner,64506,0,22022,11900 +H237,east,tenant,29564,0,1310,9782 +H208,east,tenant,66261,28397,4503,20087 +H277,north,owner,0,19009,2693,3713 +H226,east,owner,0,17936,57627,5475 +H294,south,tenant,0,51193,0,13628 +H191,north,owner,26596,0,39707,6589 +H095,west,tenant,33226,0,1266,8414 +H335,east,owner,42796,0,0,13181 +H189,west,tenant,44025,0,1557,13642 +H186,east,tenant,30202,0,1255,6994 +H257,north,owner,0,100160,23275,32080 +H036,north,owner,28475,12204,2095,11741 +H323,west,tenant,30747,0,3606,10209 +H232,south,owner,33503,0,8268,9411 +H333,north,tenant,0,144051,3784,46157 +H074,south,tenant,45763,0,1891,13274 +H176,west,owner,26333,11285,3613,7766 +H383,west,owner,7780,0,20783,1417 +H392,east,tenant,0,15039,3576,3329 +H003,east,tenant,29242,12532,0,9041 +H012,west,owner,7698,0,6649,1977 +H184,east,tenant,72195,0,1996,23233 +H220,west,tenant,0,19891,12251,5221 diff --git a/tasks/price-index/price-index-income-distribution-d2-e0005/instruction.md b/tasks/price-index/price-index-income-distribution-d2-e0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7bad5a6214bc50a0513fc0fbc167a3d1c1a2c7c8 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0005/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 40 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-e0005/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-e0005/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0005/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-e0005/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-e0005/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0005/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-e0017/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-e0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-e0017/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-e0017/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..d144b899a4c0fb7ddc28e11194dd86c27ff51c1c --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0017/environment/workdir/households.csv @@ -0,0 +1,41 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H387,north,tenant,32227,0,11138,10733 +H057,west,tenant,9652,0,30328,3038 +H288,west,owner,13868,0,13008,2820 +H233,west,owner,0,6201,21557,1310 +H079,east,tenant,34291,0,5646,6301 +H260,west,tenant,0,59556,0,16638 +H014,east,owner,10607,0,15522,2571 +H268,north,tenant,9144,0,19952,3039 +H398,west,tenant,7756,0,4573,1918 +H096,west,owner,4831,2070,15096,1458 +H147,north,tenant,0,20856,15280,7020 +H207,south,tenant,9926,4254,7430,4011 +H271,south,owner,7964,3413,27726,3655 +H219,west,owner,15717,0,14036,5196 +H232,north,owner,0,17992,722,4469 +H190,east,tenant,9678,0,1606,2389 +H310,east,owner,0,14363,17082,4406 +H118,west,tenant,15609,6689,8729,5752 +H004,north,owner,38569,0,1805,10178 +H142,south,tenant,0,23851,8110,7310 +H292,south,tenant,14956,0,589,4290 +H345,west,tenant,36751,0,1377,8289 +H013,north,tenant,16603,0,17291,4454 +H033,north,tenant,10305,0,19916,1949 +H259,west,tenant,19874,8518,672,7624 +H115,south,owner,20988,0,562,5768 +H367,west,tenant,14596,6255,1671,5883 +H203,west,tenant,12514,0,10688,3014 +H040,south,owner,0,9776,282,2200 +H199,east,owner,8592,3682,23481,3194 +H348,east,owner,9897,0,3405,2046 +H227,north,owner,21934,9400,0,6324 +H090,east,owner,15801,0,18508,2904 +H022,west,tenant,10127,4340,2284,2659 +H177,west,owner,27731,0,1051,6640 +H280,north,owner,0,29970,2201,9892 +H121,east,tenant,30093,0,0,8292 +H089,east,owner,20406,8745,1329,8864 +H071,east,tenant,30918,0,838,9162 +H174,north,owner,0,30795,0,6824 diff --git a/tasks/price-index/price-index-income-distribution-d2-e0017/instruction.md b/tasks/price-index/price-index-income-distribution-d2-e0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7bad5a6214bc50a0513fc0fbc167a3d1c1a2c7c8 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0017/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 40 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-e0017/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-e0017/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0017/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-e0017/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-e0017/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-e0017/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-t0005/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-t0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-t0005/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-t0005/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..f7213f7eabffe22d1824171d49b3a564d4da7e83 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0005/environment/workdir/households.csv @@ -0,0 +1,51 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H295,east,owner,14112,0,22665,3490 +H170,north,tenant,36491,0,13447,9419 +H177,south,owner,0,75730,0,21790 +H071,west,owner,34216,0,0,6951 +H080,north,owner,45908,0,2132,13082 +H386,north,owner,0,46384,15307,10962 +H199,south,tenant,13264,5684,8748,5348 +H149,north,tenant,44565,0,11830,13754 +H354,north,tenant,34802,0,1240,8035 +H398,east,tenant,0,33183,12007,8406 +H338,south,tenant,23910,0,6530,4774 +H057,north,tenant,21667,0,9734,5408 +H308,east,tenant,38621,0,0,7434 +H378,west,tenant,81015,0,0,15776 +H050,south,tenant,22340,0,3470,6110 +H217,east,owner,0,33741,13515,9758 +H179,east,tenant,29584,0,1199,8513 +H322,south,owner,33834,14500,1467,15865 +H115,east,owner,22027,0,7049,7336 +H014,west,tenant,0,26381,0,7206 +H125,north,tenant,17977,0,0,5635 +H104,south,owner,24313,10420,3297,10214 +H329,east,tenant,20190,8653,1330,9184 +H035,south,tenant,49966,0,1224,9173 +H325,east,owner,44724,0,1672,13629 +H264,west,owner,40871,17516,1629,15521 +H364,east,tenant,21720,0,17995,4806 +H005,west,tenant,32382,0,1424,9450 +H388,west,owner,43376,18590,15144,17410 +H372,west,owner,29063,0,9443,9200 +H191,south,owner,27124,11624,1226,11596 +H302,north,owner,38096,0,0,11573 +H121,east,owner,7282,0,11447,1519 +H185,north,tenant,38837,0,4734,12234 +H228,east,owner,20382,0,5595,5072 +H240,west,tenant,64639,0,1680,20130 +H269,north,owner,0,29809,0,9132 +H010,west,tenant,21557,0,9413,6338 +H343,north,owner,0,45065,2200,13614 +H227,east,tenant,47253,0,0,16040 +H027,east,owner,24849,0,16752,7428 +H002,north,tenant,41460,0,1590,9316 +H162,west,owner,31672,0,13264,5738 +H025,east,tenant,39721,0,1917,10100 +H280,south,owner,12127,5198,2885,5649 +H032,south,tenant,11638,4988,34305,5404 +H389,east,owner,12940,0,7405,3258 +H214,east,tenant,49808,0,6902,13344 +H167,south,owner,34979,0,5090,7253 +H095,south,tenant,34831,0,5140,10455 diff --git a/tasks/price-index/price-index-income-distribution-d2-t0005/instruction.md b/tasks/price-index/price-index-income-distribution-d2-t0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0e62198724d871b46046f165acad51a6552173ca --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0005/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 50 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-t0005/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-t0005/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0005/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-t0005/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-t0005/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0005/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-t0017/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-t0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-t0017/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-t0017/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..7f417d5679bc3fdb9540553d0067b68aeabb15eb --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0017/environment/workdir/households.csv @@ -0,0 +1,46 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H120,east,owner,42292,0,1684,13012 +H146,north,owner,0,52142,2082,10170 +H354,north,tenant,25950,0,4254,7630 +H292,south,tenant,8732,3742,12059,3941 +H216,north,owner,0,19731,24383,5526 +H046,south,owner,26924,0,41839,8509 +H293,west,tenant,15268,0,26008,4868 +H240,north,owner,19841,8504,16186,8802 +H013,north,owner,0,24517,21184,5799 +H350,east,owner,68490,0,2360,18200 +H356,north,owner,0,12983,24844,3142 +H314,east,owner,0,52587,0,12130 +H069,north,tenant,34778,0,1329,10492 +H232,south,tenant,0,29927,6979,6003 +H344,south,owner,35503,0,1707,11616 +H191,west,owner,0,15449,2430,4449 +H182,north,tenant,17081,0,10501,4819 +H058,south,tenant,0,18197,15052,3296 +H273,south,tenant,31310,0,0,7853 +H268,east,tenant,22294,9555,13788,9151 +H388,south,tenant,60658,0,4785,11486 +H346,south,tenant,32160,0,765,8764 +H294,north,tenant,16842,7218,12734,4858 +H371,west,tenant,0,26392,2102,8220 +H250,south,owner,11286,0,17284,3507 +H054,west,owner,19630,0,17349,4874 +H028,east,tenant,36974,0,6223,12065 +H068,east,owner,0,35709,10731,7522 +H385,east,tenant,0,34967,7842,7897 +H035,west,owner,13493,0,18617,4448 +H030,north,owner,86618,0,0,28826 +H219,south,owner,56566,0,0,11038 +H223,north,tenant,0,46261,1637,12468 +H167,west,tenant,23722,10166,0,11235 +H360,south,tenant,0,37580,0,11882 +H341,north,owner,0,24224,2030,5384 +H077,west,tenant,24347,0,53932,6127 +H211,east,owner,0,25868,7727,6827 +H205,north,owner,0,39246,0,9716 +H148,west,owner,0,29055,15755,6736 +H009,west,tenant,32205,0,0,8391 +H287,north,owner,46881,0,1262,9086 +H399,south,owner,33097,14184,0,10693 +H324,south,tenant,16787,7194,0,5183 +H333,south,owner,36384,0,17831,8551 diff --git a/tasks/price-index/price-index-income-distribution-d2-t0017/instruction.md b/tasks/price-index/price-index-income-distribution-d2-t0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3896fa7b22030ba24be57c1d0820cc18d568b30b --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0017/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 45 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-t0017/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-t0017/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0017/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-t0017/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-t0017/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0017/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-t0029/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-t0029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0029/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-t0029/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-t0029/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..dcdf367a1c5b1106d7eea83f6e07dcdbc95d273a --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0029/environment/workdir/households.csv @@ -0,0 +1,61 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H206,west,owner,28517,12222,1261,10345 +H299,east,tenant,59877,25662,10289,18505 +H197,west,owner,30785,0,3925,5698 +H060,east,owner,25769,0,7463,5354 +H175,south,owner,19429,8327,16624,8410 +H009,west,owner,12100,5186,10539,5380 +H018,south,tenant,40372,0,0,10011 +H026,east,tenant,79979,0,2835,16760 +H328,west,tenant,0,52937,0,17181 +H234,south,tenant,39648,0,14644,8662 +H224,west,owner,23094,0,11007,5291 +H035,west,tenant,43961,0,16274,11614 +H102,north,tenant,43439,18617,15358,14282 +H377,south,tenant,0,44758,1472,9685 +H094,east,owner,29464,12627,24111,8310 +H122,north,owner,32196,0,1180,8912 +H275,east,tenant,63456,27195,0,19152 +H387,east,owner,10640,0,21733,3564 +H130,south,tenant,5452,0,22366,1481 +H085,north,owner,66159,0,2408,12413 +H270,east,tenant,29466,12628,16579,14227 +H162,south,owner,73293,0,0,17040 +H199,west,owner,20619,8836,763,7265 +H134,west,tenant,0,26555,2267,6553 +H210,south,tenant,0,63596,1558,21519 +H121,east,owner,34121,0,49397,11136 +H345,north,tenant,9601,0,20879,2219 +H334,south,owner,30329,0,15640,7534 +H194,south,tenant,0,31751,1199,10015 +H144,west,tenant,29549,12664,1775,12692 +H359,south,owner,36365,0,842,6699 +H252,north,tenant,42851,0,6726,12344 +H302,south,tenant,55430,0,0,18433 +H296,south,owner,64811,0,0,18365 +H376,east,owner,51066,0,2245,12156 +H068,east,tenant,52675,0,2120,11906 +H052,north,owner,23545,0,9448,6914 +H152,east,owner,32198,0,1159,9468 +H104,south,owner,0,31949,0,6453 +H200,east,owner,90916,0,3575,22475 +H166,west,tenant,48410,0,34574,15392 +H107,west,owner,53444,0,2671,10425 +H084,south,tenant,41321,17709,0,14198 +H214,north,owner,0,16136,30777,5269 +H374,west,owner,60204,0,0,20414 +H093,south,owner,24862,0,30797,5937 +H309,south,owner,36820,0,5371,8517 +H211,south,tenant,64338,0,0,21305 +H269,east,tenant,27346,0,6297,9174 +H135,south,tenant,0,46329,2250,14223 +H005,north,owner,54251,0,6344,12802 +H055,north,tenant,15146,0,19129,3219 +H208,south,owner,41458,0,26479,10576 +H312,south,tenant,74113,0,0,22831 +H310,north,tenant,37763,0,1114,8718 +H292,north,owner,0,56819,33678,10522 +H239,east,owner,11384,4879,40636,4990 +H265,east,owner,0,29593,34757,8827 +H384,south,tenant,47115,0,4845,14599 +H127,west,owner,0,32917,34768,7510 diff --git a/tasks/price-index/price-index-income-distribution-d2-t0029/instruction.md b/tasks/price-index/price-index-income-distribution-d2-t0029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec5853474029e7d5011e033a66108f0e6589f921 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0029/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 60 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-t0029/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-t0029/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0029/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-t0029/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-t0029/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0029/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-t0041/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-t0041/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0041/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-t0041/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-t0041/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..0997931d711182b618d953ad584706c84835ebf8 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0041/environment/workdir/households.csv @@ -0,0 +1,41 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H397,south,tenant,67546,0,2925,14346 +H258,south,tenant,0,39260,27365,10919 +H305,south,tenant,52486,0,2263,14593 +H094,west,owner,137052,0,4420,35615 +H240,west,tenant,15776,0,49416,5327 +H117,east,tenant,56926,24397,0,23967 +H343,south,tenant,30340,0,1104,8155 +H095,west,tenant,35749,15321,2145,11332 +H297,west,owner,50046,0,1809,10306 +H179,north,tenant,38091,0,28294,8809 +H137,north,owner,45510,0,1972,8542 +H304,east,tenant,24912,0,2074,4898 +H140,east,owner,57074,0,0,10302 +H199,south,owner,0,67593,0,13432 +H129,south,owner,56767,0,4910,13387 +H116,south,tenant,23755,0,23056,6318 +H191,west,tenant,69809,0,0,23694 +H380,south,tenant,0,30076,0,6044 +H346,east,owner,59370,25444,10715,19718 +H375,west,owner,23501,10072,86406,7216 +H170,east,tenant,0,77994,11726,16069 +H127,north,owner,34477,0,9629,10547 +H351,east,owner,69244,29676,8280,30402 +H015,west,owner,42317,0,22238,10128 +H233,east,tenant,44142,0,19800,10716 +H396,east,owner,25103,0,31811,6510 +H288,east,tenant,45571,0,35369,12530 +H045,south,tenant,14534,0,33947,4006 +H217,north,tenant,25608,10975,3762,10260 +H252,south,tenant,40680,0,30600,7628 +H275,west,tenant,55122,0,0,15596 +H243,east,tenant,38494,16497,7944,13290 +H395,south,tenant,44506,0,0,11046 +H205,south,tenant,48775,0,21152,13099 +H043,west,owner,6390,2739,20019,2721 +H174,east,tenant,39475,0,5004,8659 +H262,east,owner,12091,5182,2302,5071 +H268,east,tenant,26570,11387,845,10000 +H255,east,tenant,23350,0,872,7907 +H340,north,owner,0,16690,30016,5642 diff --git a/tasks/price-index/price-index-income-distribution-d2-t0041/instruction.md b/tasks/price-index/price-index-income-distribution-d2-t0041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7bad5a6214bc50a0513fc0fbc167a3d1c1a2c7c8 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0041/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 40 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-t0041/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-t0041/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0041/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-t0041/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-t0041/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0041/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-t0053/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-t0053/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0053/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-t0053/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-t0053/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..045512a1a46496c5c2091132fcfb5d1735c88509 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0053/environment/workdir/households.csv @@ -0,0 +1,46 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H227,north,owner,9955,0,22059,3094 +H223,north,tenant,21935,0,10390,6084 +H071,east,owner,0,42126,1147,7721 +H022,west,owner,0,41567,7261,9375 +H263,south,tenant,0,30667,16621,6413 +H182,west,owner,29659,12711,1720,8924 +H121,west,owner,65442,0,1800,16646 +H334,east,tenant,24427,10468,0,10664 +H076,north,owner,30935,0,1070,7725 +H275,north,tenant,75209,0,5449,25215 +H230,south,tenant,16457,7053,41671,4593 +H363,north,tenant,60898,0,0,11770 +H357,east,owner,30834,0,15989,5577 +H371,east,owner,0,71511,0,19922 +H041,east,owner,0,20506,1870,4970 +H034,east,owner,49820,0,0,9205 +H165,west,owner,20513,0,2419,3862 +H169,north,owner,39653,0,1358,7461 +H108,east,owner,50229,0,0,12172 +H053,north,owner,0,57958,8649,16388 +H220,west,owner,0,33049,3846,6428 +H032,east,tenant,38950,0,5196,10438 +H056,north,owner,10163,4356,17462,3220 +H153,west,owner,0,19577,22823,3825 +H251,east,owner,35251,0,0,8061 +H201,west,owner,14063,6027,21542,4093 +H141,east,tenant,10729,0,22765,2416 +H159,south,owner,41452,0,1113,7872 +H326,north,owner,0,26880,1224,5539 +H055,east,tenant,5177,0,20671,1581 +H342,north,tenant,28667,0,0,6743 +H317,south,tenant,63274,0,16827,15334 +H373,north,tenant,27248,11678,28273,7454 +H216,south,tenant,27048,0,10333,6355 +H280,south,owner,56590,0,0,13081 +H117,east,tenant,13684,0,14348,3783 +H033,west,tenant,0,25993,6139,7851 +H260,west,owner,53636,0,0,17348 +H279,east,owner,40756,0,0,7528 +H266,north,tenant,36254,0,18801,8164 +H324,west,owner,0,27705,20125,6012 +H007,north,tenant,16986,7280,27101,7300 +H185,north,owner,0,54345,18963,16148 +H027,north,owner,0,36437,0,12186 +H028,west,tenant,0,13192,11322,3095 diff --git a/tasks/price-index/price-index-income-distribution-d2-t0053/instruction.md b/tasks/price-index/price-index-income-distribution-d2-t0053/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3896fa7b22030ba24be57c1d0820cc18d568b30b --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0053/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 45 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-t0053/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-t0053/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0053/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-t0053/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-t0053/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0053/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-t0065/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-t0065/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0065/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-t0065/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-t0065/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..5e8aa9107d2d03f0e64ee5551f6dac208551af70 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0065/environment/workdir/households.csv @@ -0,0 +1,61 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H212,west,owner,33543,0,15359,10642 +H247,west,owner,105599,0,53363,30375 +H290,south,owner,44579,0,0,15113 +H334,east,tenant,21379,0,11295,7185 +H009,south,owner,39853,0,2005,8595 +H261,east,owner,0,15984,2454,4435 +H014,north,tenant,31815,0,1227,6932 +H115,east,owner,51805,0,0,9549 +H210,east,tenant,15654,0,23067,3691 +H056,south,owner,139421,0,5873,28345 +H153,west,owner,0,76767,2126,16646 +H350,north,owner,62692,0,51551,12441 +H127,south,tenant,19089,0,7632,4970 +H208,south,tenant,15553,0,15908,4959 +H048,west,owner,69261,29684,14139,25116 +H354,south,tenant,28198,0,15089,5744 +H124,west,owner,18756,8038,14134,6346 +H044,east,tenant,38003,0,1061,6948 +H082,south,tenant,29685,0,2922,7937 +H053,east,owner,49209,0,0,14499 +H285,east,owner,0,10146,23344,2566 +H254,south,tenant,16182,6935,799,4321 +H326,east,tenant,17558,0,747,3669 +H046,east,tenant,115808,0,0,23440 +H109,south,tenant,35773,0,1537,9807 +H126,south,owner,0,48059,0,13383 +H157,west,owner,23773,10189,0,8723 +H183,north,owner,0,21869,994,3985 +H282,west,owner,3332,1428,18545,897 +H336,east,owner,0,39204,31948,9105 +H133,south,owner,31871,13659,1711,12311 +H227,east,owner,0,30320,20777,9991 +H071,south,tenant,93140,0,0,26232 +H312,north,owner,90534,0,3371,21796 +H173,east,owner,0,50608,1590,15243 +H353,south,owner,83683,0,2987,15439 +H061,west,tenant,24905,0,22570,6939 +H164,west,tenant,32277,0,3371,6503 +H357,south,owner,21557,0,23189,4912 +H393,south,tenant,48331,0,49593,11953 +H110,east,tenant,27020,0,14151,4975 +H185,north,tenant,13830,0,5260,3162 +H295,west,owner,28338,0,2701,5716 +H383,north,tenant,26301,11272,0,9801 +H012,north,tenant,53627,0,2005,13539 +H328,east,tenant,58554,0,5314,12694 +H170,south,tenant,0,31867,21886,8170 +H142,east,tenant,166716,0,0,41876 +H368,east,owner,71129,0,1793,23451 +H306,west,tenant,26505,0,0,7698 +H325,north,owner,0,36040,3825,7260 +H289,west,tenant,45172,0,26895,9280 +H269,west,tenant,27724,0,25719,7122 +H026,west,tenant,0,41534,5626,10142 +H245,east,tenant,0,54013,5441,12957 +H045,south,owner,9688,0,4526,2202 +H168,north,owner,0,35831,1259,10222 +H131,east,tenant,6239,0,2470,1192 +H305,north,tenant,71371,0,88832,15417 +H365,west,owner,51466,0,2317,14144 diff --git a/tasks/price-index/price-index-income-distribution-d2-t0065/instruction.md b/tasks/price-index/price-index-income-distribution-d2-t0065/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec5853474029e7d5011e033a66108f0e6589f921 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0065/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 60 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-t0065/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-t0065/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0065/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-t0065/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-t0065/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0065/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d2-t0077/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d2-t0077/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0077/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d2-t0077/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d2-t0077/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..cf806a70a5673e5f10e4c232fbf4848c3cdb531c --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0077/environment/workdir/households.csv @@ -0,0 +1,61 @@ +household_id,region,tenure,wages,self_employment_income,pensions_and_benefits,taxes_paid +H362,north,owner,11449,0,35010,2948 +H393,west,owner,14023,0,18404,4296 +H203,east,tenant,30406,13031,20215,14081 +H390,west,owner,23096,9898,3122,6524 +H204,south,tenant,8206,0,32522,1708 +H041,south,owner,0,59942,0,12594 +H328,west,tenant,42249,18106,5944,19186 +H290,north,owner,64318,0,19221,20866 +H128,east,owner,27501,11786,15222,9980 +H387,north,tenant,6469,2773,13483,2459 +H013,south,owner,94335,0,2322,19542 +H057,east,owner,0,81453,6184,25295 +H372,east,tenant,0,45443,13735,13428 +H067,south,owner,51854,0,4248,13887 +H111,west,owner,32601,0,1150,5974 +H040,east,tenant,22998,0,26660,4522 +H281,west,tenant,26199,0,4514,5454 +H356,south,tenant,39145,0,19139,12654 +H379,west,tenant,0,18149,771,5976 +H258,south,tenant,70337,0,2329,23797 +H101,west,owner,44590,0,0,10636 +H333,east,owner,47391,0,0,13658 +H384,north,owner,24069,10316,64928,6516 +H217,north,tenant,31315,0,18846,6095 +H180,north,tenant,33301,0,1358,5995 +H100,west,tenant,69641,0,0,15249 +H296,north,owner,34285,14693,13593,14350 +H065,north,owner,24066,0,2351,7386 +H323,north,tenant,31313,0,0,6127 +H086,west,owner,21631,0,36325,5457 +H161,west,owner,56659,0,5082,16168 +H127,east,owner,48986,0,16151,10776 +H134,west,tenant,125350,0,0,25376 +H350,west,owner,0,22232,16922,5334 +H324,west,owner,32194,13797,3868,9818 +H271,south,owner,0,47124,6986,12157 +H209,west,owner,28641,0,28755,5801 +H307,east,tenant,32150,0,0,5930 +H248,south,tenant,85467,36629,0,29303 +H286,north,tenant,20175,0,5560,6392 +H351,west,owner,93727,0,3793,31737 +H278,east,owner,44197,18941,0,11875 +H157,east,owner,10315,0,21142,2181 +H097,west,owner,50363,0,0,10977 +H208,west,owner,13339,5716,13365,3988 +H160,north,tenant,21862,9370,1336,9175 +H348,west,owner,0,10347,17043,2103 +H329,north,owner,32407,0,1419,6883 +H162,east,tenant,21295,9127,4165,7422 +H370,south,tenant,29641,12703,5301,12347 +H115,east,owner,26177,11218,3507,9047 +H220,east,owner,38830,16641,7144,18596 +H302,north,owner,38120,0,1764,9525 +H349,west,tenant,47483,0,0,8983 +H231,north,tenant,29953,0,15747,5451 +H361,north,tenant,24672,0,52517,5323 +H399,south,owner,137450,0,14587,46682 +H337,east,owner,10152,4351,25436,4085 +H159,south,owner,33040,0,10001,8918 +H023,north,tenant,23946,0,20918,7955 diff --git a/tasks/price-index/price-index-income-distribution-d2-t0077/instruction.md b/tasks/price-index/price-index-income-distribution-d2-t0077/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec5853474029e7d5011e033a66108f0e6589f921 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0077/instruction.md @@ -0,0 +1,24 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components of 60 households from a survey. Each household is one observation. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the households, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 households). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `households`: the number of households, an integer. +- `mean_income` and `median_income`: of household disposable income, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `households_at_risk`: the number of households with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all households, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d2-t0077/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d2-t0077/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0077/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d2-t0077/tests/verify.py b/tasks/price-index/price-index-income-distribution-d2-t0077/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d2-t0077/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-e0009/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-e0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-e0009/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-e0009/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..abe81822e66cad2e576d452626ed725f902dbb21 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0009/environment/workdir/households.csv @@ -0,0 +1,41 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H239,south,owner,3,1,110680,0,30129,37562 +H301,east,tenant,4,2,84367,0,6561,23113 +H111,west,owner,2,0,69691,0,10436,15802 +H293,south,owner,2,2,47797,0,11657,11259 +H356,west,tenant,1,0,0,44064,2173,11320 +H220,west,tenant,4,0,37680,16149,5288,17372 +H240,north,tenant,1,2,11666,5000,6365,4236 +H249,south,tenant,2,0,48368,0,2259,9382 +H186,south,owner,4,2,158698,0,0,35033 +H253,north,tenant,2,1,41941,17974,7300,19255 +H046,east,owner,3,0,60076,0,2785,20193 +H290,east,owner,1,0,26719,0,8594,6207 +H296,east,owner,1,2,0,43058,0,12920 +H095,west,tenant,1,0,0,177035,0,49228 +H066,south,tenant,2,0,39789,17052,42869,13873 +H302,south,owner,2,2,0,110243,18975,34374 +H160,south,tenant,2,0,0,136861,21505,32503 +H072,west,tenant,4,3,27691,0,23638,7775 +H279,north,tenant,1,2,23475,0,1066,4880 +H045,west,owner,1,0,52247,22391,19607,15832 +H215,east,tenant,2,2,30864,0,0,7489 +H088,east,tenant,1,2,0,23465,837,5259 +H291,west,tenant,1,0,41857,0,0,12579 +H297,east,owner,3,0,212335,0,24374,44982 +H354,west,owner,3,2,71584,0,0,15397 +H185,south,tenant,3,1,37116,0,33051,9556 +H128,west,owner,2,0,78660,0,0,15206 +H014,south,tenant,2,1,56443,0,5989,15806 +H377,north,tenant,2,2,38281,0,0,10315 +H193,north,tenant,2,1,30674,0,911,6913 +H244,north,owner,2,2,21646,0,29625,5132 +H214,south,tenant,2,3,45535,0,0,13008 +H056,east,owner,2,1,57731,0,9423,11885 +H154,south,tenant,3,1,27490,0,12853,7658 +H198,east,tenant,3,0,55577,23819,38108,23382 +H280,south,tenant,1,2,47764,0,0,10955 +H201,west,tenant,1,2,0,36667,62458,12342 +H107,south,tenant,4,2,0,68048,0,15499 +H336,west,tenant,1,2,72745,0,3091,20655 +H197,south,owner,2,0,0,37219,1417,11501 diff --git a/tasks/price-index/price-index-income-distribution-d3-e0009/instruction.md b/tasks/price-index/price-index-income-distribution-d3-e0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a9534a0eddeeb29dd69e156a01b6b0f366723d36 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0009/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 40 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-e0009/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-e0009/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0009/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-e0009/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-e0009/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0009/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-e0021/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-e0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-e0021/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-e0021/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..4df30e78140ebdd659a7f6cd18c85ef08b729158 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0021/environment/workdir/households.csv @@ -0,0 +1,41 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H168,north,owner,2,0,32594,0,4321,6684 +H017,east,owner,1,2,7063,3027,1307,3103 +H240,east,tenant,2,1,64184,0,7761,12658 +H214,south,tenant,4,0,48777,20905,0,16851 +H245,south,tenant,4,0,199872,0,61147,66067 +H063,north,tenant,3,2,0,204044,128126,58731 +H041,north,tenant,2,0,19732,8457,48151,9512 +H183,east,owner,2,1,7763,3327,18387,2464 +H025,west,owner,2,3,38681,0,3960,11331 +H363,east,tenant,4,3,0,46027,1217,14833 +H354,south,owner,2,1,49152,0,5694,15052 +H347,south,tenant,2,2,81857,0,133071,17706 +H157,west,owner,3,2,42479,18205,5632,17528 +H261,east,owner,1,1,15189,6509,770,5839 +H049,north,owner,3,3,12865,5513,5445,5378 +H139,north,tenant,4,0,0,140648,61209,28550 +H094,south,owner,2,2,91820,0,3053,25198 +H161,east,tenant,1,2,4683,0,9501,871 +H107,east,owner,1,3,0,11560,23781,3765 +H250,north,tenant,2,0,38697,0,80279,10626 +H192,west,tenant,2,0,37328,0,0,9376 +H133,south,owner,2,0,8787,0,253,1587 +H371,east,owner,2,0,60362,0,15202,13774 +H001,north,tenant,2,1,23262,9969,0,8900 +H074,south,owner,2,2,17985,7708,0,8222 +H394,west,owner,1,0,0,29679,4880,8309 +H314,east,tenant,3,3,230377,0,27413,73570 +H262,west,tenant,1,1,11908,0,1771,3803 +H230,west,owner,4,3,28703,0,20748,8125 +H202,west,owner,1,1,74675,0,9425,20681 +H378,north,owner,3,0,0,7514,824,1728 +H106,north,tenant,2,0,48438,0,6295,9832 +H070,south,tenant,4,2,276369,0,25225,61644 +H316,south,tenant,4,2,42292,0,18255,13551 +H068,east,tenant,2,1,75146,0,2266,23209 +H396,south,tenant,4,0,0,68735,45423,12873 +H337,south,owner,2,3,105594,0,15167,30623 +H057,north,owner,2,0,59403,0,1712,18428 +H146,south,tenant,1,3,9423,0,0,1963 +H392,north,owner,4,0,0,8002,6110,2446 diff --git a/tasks/price-index/price-index-income-distribution-d3-e0021/instruction.md b/tasks/price-index/price-index-income-distribution-d3-e0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a9534a0eddeeb29dd69e156a01b6b0f366723d36 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0021/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 40 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-e0021/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-e0021/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0021/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-e0021/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-e0021/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-e0021/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-t0009/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-t0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-t0009/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-t0009/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..d54f16d681c1dc0abedd0cf68c49ec9f8b25ca81 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0009/environment/workdir/households.csv @@ -0,0 +1,46 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H264,north,tenant,3,1,47352,0,1841,11295 +H272,west,tenant,2,3,40118,0,0,10188 +H306,north,tenant,2,2,28674,0,15629,9383 +H015,north,tenant,4,1,174034,74586,19210,78845 +H230,north,owner,1,0,110565,0,11910,21716 +H329,east,tenant,4,3,147049,0,0,43299 +H083,west,tenant,2,0,38964,0,39082,9376 +H181,south,tenant,4,1,0,44529,0,12835 +H281,east,owner,2,0,0,85554,42015,21380 +H008,west,owner,2,2,0,163256,6480,40766 +H075,south,owner,1,0,25215,0,0,6962 +H318,east,tenant,2,2,14608,0,1376,4089 +H064,west,tenant,4,0,30384,13022,41220,14020 +H265,west,owner,1,3,30922,13252,1391,13270 +H305,east,owner,1,0,30068,0,0,8224 +H166,south,tenant,2,1,0,39401,5720,9770 +H159,south,tenant,1,0,22132,0,7134,7357 +H245,east,tenant,1,2,23707,0,953,7660 +H394,north,owner,1,2,0,23493,847,4584 +H095,west,owner,1,2,28848,0,14079,8254 +H354,north,tenant,2,1,47118,0,0,14233 +H200,north,owner,1,0,68512,0,0,19050 +H387,north,owner,2,3,0,70791,21516,23412 +H002,north,owner,4,2,31903,0,31801,9228 +H103,south,owner,3,0,72706,31160,2869,30442 +H373,south,owner,2,2,16984,0,858,3920 +H024,west,owner,2,2,12029,5155,8121,3480 +H050,west,owner,4,3,0,133783,5606,28093 +H260,west,owner,2,1,0,72518,0,24088 +H370,west,owner,4,2,67016,0,0,18469 +H269,west,tenant,4,0,0,130499,62613,39683 +H185,west,owner,2,1,10332,0,20856,2411 +H146,east,owner,1,2,15921,0,19535,4510 +H047,south,tenant,2,1,53023,0,6625,13288 +H114,south,tenant,1,3,29486,0,1363,6274 +H226,east,owner,2,2,12700,0,2953,2404 +H276,west,owner,4,2,50483,0,26848,15747 +H110,west,tenant,3,0,58162,0,23091,16536 +H016,north,owner,2,0,74744,0,2131,19683 +H274,north,tenant,3,0,45616,0,44509,9685 +H382,south,tenant,2,2,96736,0,3029,18843 +H278,south,owner,2,0,0,14642,537,2683 +H040,east,owner,1,3,5866,0,1398,1488 +H309,west,tenant,4,2,31245,0,56346,6170 +H030,west,owner,1,0,24345,0,0,5608 diff --git a/tasks/price-index/price-index-income-distribution-d3-t0009/instruction.md b/tasks/price-index/price-index-income-distribution-d3-t0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f22f667218b29cf4217b7e80b70ef2a83ecc5bd5 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0009/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 45 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-t0009/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-t0009/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0009/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-t0009/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-t0009/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0009/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-t0021/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-t0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-t0021/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-t0021/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..8b1395748f9c0bfcda068db6ae3c6cb1594da313 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0021/environment/workdir/households.csv @@ -0,0 +1,46 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H002,west,owner,3,2,0,103575,2585,31737 +H303,south,tenant,3,0,0,175877,65819,48972 +H128,south,tenant,2,2,127308,0,6569,27100 +H216,north,owner,2,3,40045,0,31612,11988 +H241,west,tenant,2,1,81252,34822,18921,31009 +H110,east,owner,1,0,27356,0,2381,7077 +H076,north,owner,2,1,38582,0,1640,11488 +H386,north,owner,2,1,66391,0,3440,13582 +H124,west,owner,2,1,142566,0,15165,33527 +H099,north,owner,2,2,23470,0,62746,6542 +H297,north,tenant,1,2,30298,12985,6329,9201 +H317,east,tenant,1,2,21854,9366,11402,6106 +H162,west,owner,1,3,199052,85308,8602,89787 +H036,north,tenant,2,0,43917,18822,48639,16830 +H370,south,owner,2,2,31697,0,22018,9475 +H316,south,owner,2,0,40944,17548,4718,18056 +H234,west,owner,3,0,73367,0,25181,20135 +H012,north,owner,1,0,33463,14342,1262,10406 +H062,north,owner,1,3,35177,15076,1904,12903 +H079,south,tenant,2,2,20034,0,45280,4478 +H261,east,tenant,2,2,206530,0,0,47844 +H179,north,owner,2,3,74502,0,7141,20959 +H092,east,owner,2,0,0,61737,0,15997 +H207,south,tenant,1,2,45459,19482,35337,21288 +H248,south,tenant,2,1,0,43117,65661,14248 +H388,east,owner,4,2,84612,0,0,18634 +H154,east,tenant,3,0,202307,0,124062,40012 +H052,south,owner,3,0,100632,43128,6042,41179 +H028,south,tenant,3,0,114107,0,0,29196 +H361,north,tenant,1,3,105935,0,3658,24305 +H042,north,owner,3,3,49784,0,1823,16625 +H348,east,tenant,2,3,64594,0,0,13512 +H026,west,tenant,2,0,0,110625,0,23989 +H171,west,owner,3,0,72257,0,6972,23924 +H165,north,tenant,3,0,42461,0,85245,12145 +H357,south,owner,2,0,14743,0,30722,4298 +H220,north,owner,2,0,25536,0,92882,5863 +H137,east,owner,2,3,87202,0,0,28164 +H039,south,tenant,2,3,113155,0,12394,38011 +H211,south,owner,4,2,82252,0,23713,25391 +H085,east,owner,4,0,343473,0,366577,87117 +H371,east,tenant,1,3,29009,12432,1996,12319 +H219,west,owner,2,0,94551,0,8634,27873 +H035,north,owner,2,2,118065,0,0,23248 +H229,east,tenant,1,1,0,36591,10097,6997 diff --git a/tasks/price-index/price-index-income-distribution-d3-t0021/instruction.md b/tasks/price-index/price-index-income-distribution-d3-t0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f22f667218b29cf4217b7e80b70ef2a83ecc5bd5 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0021/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 45 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-t0021/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-t0021/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0021/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-t0021/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-t0021/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0021/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-t0033/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-t0033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0033/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-t0033/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-t0033/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..a795b877020f4a42ce997e2a03e8bd45f1dbf327 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0033/environment/workdir/households.csv @@ -0,0 +1,41 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H326,north,tenant,1,1,31583,0,25347,10400 +H006,east,owner,2,2,20695,8870,71167,8207 +H157,south,tenant,1,0,0,58159,1574,12466 +H176,east,owner,2,0,58453,0,24921,14161 +H377,south,tenant,1,2,47443,0,5740,15242 +H101,north,tenant,1,3,44297,0,1256,14100 +H035,east,owner,2,3,31511,13505,1756,9775 +H384,north,tenant,3,1,172352,0,5977,48713 +H354,south,tenant,1,2,0,10152,3590,3264 +H349,west,owner,3,2,86392,0,62763,18393 +H140,west,tenant,2,0,0,57482,5445,17516 +H268,west,tenant,3,2,35786,0,1144,10327 +H161,north,tenant,1,3,47606,0,19290,10688 +H089,west,tenant,4,0,0,143384,4929,41711 +H182,south,owner,2,0,11900,0,40172,2783 +H061,west,tenant,1,0,8684,0,320,1961 +H367,south,tenant,4,0,75879,0,0,19014 +H395,south,tenant,4,0,199955,85695,0,96852 +H246,west,owner,2,0,213541,0,26222,66028 +H197,south,tenant,2,0,31569,0,4016,10368 +H153,east,owner,4,0,106647,0,2656,24326 +H333,north,owner,2,0,35244,15104,11522,15132 +H163,north,owner,1,1,48169,0,4964,16110 +H386,east,tenant,4,3,0,81107,9298,27071 +H063,west,tenant,2,0,144106,0,0,40276 +H254,north,owner,2,0,24033,0,12403,7831 +H107,east,owner,4,1,0,23343,13940,6821 +H027,north,owner,1,3,4786,0,11959,1020 +H070,south,tenant,1,1,26485,0,1206,6914 +H191,east,owner,1,0,9553,4094,1887,2823 +H088,south,tenant,2,2,0,11062,1012,2896 +H192,south,tenant,1,0,2715,1164,7406,813 +H120,south,owner,2,3,34088,0,0,10984 +H341,west,owner,4,0,39864,0,1420,9688 +H159,east,owner,1,3,28531,0,9680,7711 +H287,east,owner,2,0,23926,0,14692,7326 +H225,south,owner,2,1,32150,0,35776,9831 +H238,south,owner,1,0,28678,0,11976,6180 +H056,east,tenant,3,1,0,52896,2231,14763 +H172,west,owner,3,0,62848,0,6070,12186 diff --git a/tasks/price-index/price-index-income-distribution-d3-t0033/instruction.md b/tasks/price-index/price-index-income-distribution-d3-t0033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a9534a0eddeeb29dd69e156a01b6b0f366723d36 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0033/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 40 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-t0033/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-t0033/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0033/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-t0033/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-t0033/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0033/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-t0045/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-t0045/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0045/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-t0045/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-t0045/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..10879680fc3727cf1cc71f14532b9127311bde59 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0045/environment/workdir/households.csv @@ -0,0 +1,51 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H070,east,owner,2,2,48499,0,42295,9238 +H026,north,tenant,2,1,87007,0,11606,20375 +H270,west,tenant,2,3,0,138330,3629,31803 +H211,west,owner,1,1,73791,0,2077,24393 +H137,west,tenant,2,3,59098,0,0,11723 +H029,south,owner,2,1,43434,18615,0,19760 +H073,east,owner,3,0,57745,0,3052,15082 +H224,north,owner,1,0,125235,0,10207,28223 +H328,west,tenant,3,0,6721,2881,8198,3005 +H147,east,tenant,1,2,0,34547,4134,8475 +H084,south,owner,2,2,95968,0,10150,29570 +H083,north,tenant,4,1,0,72476,0,20720 +H038,west,owner,1,0,0,51273,6917,13812 +H050,north,owner,2,1,84589,0,8321,26684 +H273,west,tenant,2,0,41299,0,1009,13612 +H014,west,tenant,4,0,52160,0,0,9765 +H025,south,tenant,2,3,0,58932,24729,18119 +H003,east,owner,2,0,63063,0,0,20114 +H248,south,tenant,2,2,45516,0,1915,12527 +H189,north,tenant,4,0,0,17794,6862,5644 +H142,north,tenant,2,3,303593,0,11966,58543 +H006,south,owner,2,2,70285,30122,0,31009 +H288,east,tenant,3,3,49334,21143,2617,19986 +H373,east,owner,2,3,52717,22593,0,23495 +H323,east,owner,1,1,43115,0,143759,11785 +H397,west,owner,4,2,81297,0,71096,18890 +H118,north,owner,1,0,24000,10286,1612,9603 +H256,east,owner,3,1,114688,0,5350,21218 +H209,east,tenant,2,0,135268,57972,28850,50281 +H281,west,owner,2,0,0,49776,0,14143 +H395,north,tenant,3,0,78241,0,21530,26081 +H370,west,tenant,1,1,35395,0,1114,9855 +H311,west,tenant,1,0,40315,0,5980,12623 +H305,south,tenant,2,2,30363,0,13551,5616 +H294,west,tenant,1,0,43874,0,2069,14327 +H334,north,tenant,2,0,28255,12110,45469,12007 +H041,north,tenant,1,2,41715,0,0,10402 +H177,east,tenant,2,1,51291,0,2118,11671 +H087,north,tenant,1,1,115000,0,39210,27621 +H168,north,tenant,3,2,66904,28673,13314,25140 +H049,north,owner,1,0,0,151464,4491,49099 +H169,west,owner,1,3,223195,0,0,64277 +H051,south,tenant,4,2,0,42012,0,11141 +H129,north,tenant,3,2,0,104616,10145,30037 +H283,north,owner,4,3,40098,17185,0,17837 +H338,east,tenant,1,1,71772,30759,0,28049 +H379,south,tenant,1,0,18033,0,28026,4067 +H115,north,tenant,1,2,102975,0,43346,20509 +H357,west,tenant,1,3,0,97492,42801,24020 +H380,south,tenant,3,0,0,76721,6369,23395 diff --git a/tasks/price-index/price-index-income-distribution-d3-t0045/instruction.md b/tasks/price-index/price-index-income-distribution-d3-t0045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..043f8fa8fa09247a0e5e07ef53ac850543577830 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0045/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 50 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-t0045/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-t0045/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0045/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-t0045/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-t0045/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0045/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-t0057/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-t0057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0057/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-t0057/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-t0057/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..e0e2d2c4799ce569f122bc85b48c74f9925dc229 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0057/environment/workdir/households.csv @@ -0,0 +1,41 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H347,west,owner,1,2,38521,0,1521,7829 +H196,north,owner,2,0,34828,0,0,8966 +H017,north,tenant,3,3,0,48155,5548,13810 +H311,north,owner,2,3,51128,0,5459,16196 +H177,east,tenant,2,0,23065,0,2712,5397 +H189,east,owner,2,0,0,48025,4295,14641 +H372,west,tenant,2,0,59760,0,28863,19625 +H185,south,tenant,2,2,37418,0,15187,11897 +H323,east,tenant,2,3,47582,0,18927,13141 +H336,north,tenant,2,2,63706,0,7293,16373 +H243,north,owner,1,1,11516,4936,4921,4826 +H121,east,owner,3,2,34900,0,1114,6869 +H045,east,owner,2,0,54561,0,6735,12931 +H322,east,owner,2,3,48665,0,2038,13924 +H147,south,owner,1,1,11353,4865,0,5486 +H285,north,tenant,1,2,35547,0,0,11327 +H066,east,owner,4,0,0,24978,13043,6542 +H055,south,owner,4,0,29086,0,17208,7027 +H153,east,owner,2,0,0,29593,789,6262 +H208,north,owner,2,1,64675,0,2681,18352 +H100,east,tenant,1,1,4915,2106,9390,2191 +H188,east,owner,1,1,13735,0,17355,3707 +H140,south,owner,1,1,43863,18798,2805,16856 +H080,south,tenant,2,0,61648,0,1603,17087 +H151,south,owner,4,0,0,68102,0,18685 +H076,north,owner,2,1,0,73780,2053,16442 +H265,south,owner,2,2,15041,0,46503,4512 +H005,east,owner,2,0,43804,0,2261,14096 +H206,north,tenant,4,0,40186,17223,1930,12781 +H102,east,owner,1,0,0,14973,714,3334 +H009,north,tenant,4,0,14787,0,479,3610 +H343,north,owner,1,0,32162,0,8969,10654 +H064,south,tenant,2,1,15755,0,2457,4848 +H318,west,owner,2,1,0,19478,22792,6426 +H214,north,owner,4,2,12020,5151,6149,4878 +H248,east,tenant,2,0,0,36072,66948,10459 +H213,south,tenant,1,0,47439,0,0,11210 +H314,east,tenant,2,0,26240,0,49127,6704 +H357,east,owner,2,0,0,70264,3236,17723 +H113,north,tenant,1,2,27773,11903,0,11479 diff --git a/tasks/price-index/price-index-income-distribution-d3-t0057/instruction.md b/tasks/price-index/price-index-income-distribution-d3-t0057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a9534a0eddeeb29dd69e156a01b6b0f366723d36 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0057/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 40 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-t0057/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-t0057/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0057/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-t0057/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-t0057/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0057/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-t0069/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-t0069/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0069/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-t0069/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-t0069/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..9647380b3294e71f8c0c773ba188e271a8200339 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0069/environment/workdir/households.csv @@ -0,0 +1,51 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H043,south,tenant,4,0,68907,29531,0,27293 +H082,south,owner,1,1,0,19646,43068,4136 +H109,east,owner,1,0,0,23974,6133,4812 +H045,north,tenant,1,0,0,28030,845,5585 +H139,east,tenant,2,0,112669,48287,13160,30669 +H361,south,tenant,4,3,142382,0,114709,33295 +H263,north,owner,3,2,0,147908,42478,43640 +H298,south,owner,4,0,55562,23812,30431,22738 +H378,east,owner,1,2,0,37306,0,7766 +H030,west,owner,2,3,117333,0,39294,29327 +H172,east,tenant,1,0,34608,0,1158,7755 +H270,north,owner,1,0,29841,0,3427,7903 +H111,south,tenant,1,2,38819,0,1590,8340 +H232,north,owner,2,2,9706,4160,13283,4066 +H063,west,tenant,4,3,60137,0,4462,19358 +H032,south,owner,2,0,108200,46372,0,34781 +H002,north,tenant,4,1,48002,0,1287,15084 +H021,east,tenant,4,0,0,70051,8237,19695 +H254,west,tenant,2,3,38446,0,4405,9461 +H029,south,owner,1,2,0,35462,5275,7994 +H170,south,owner,2,3,43256,0,23407,14254 +H331,west,owner,3,0,0,110213,108489,23305 +H125,east,owner,2,0,25428,0,41427,8645 +H312,east,owner,2,2,25178,10791,11158,11905 +H035,south,tenant,2,1,12833,5500,2384,3861 +H358,north,tenant,2,0,79871,0,0,14576 +H278,west,owner,3,0,25497,0,86660,4935 +H382,west,owner,1,2,62703,0,0,20438 +H169,east,tenant,2,3,25003,0,25208,5943 +H065,south,tenant,2,3,92222,0,7213,16679 +H289,east,tenant,2,3,0,66487,37134,19513 +H097,north,owner,4,1,352443,0,0,67077 +H353,south,owner,1,2,75081,0,0,14993 +H011,north,tenant,1,3,30948,13264,15848,9866 +H047,west,owner,4,1,27533,0,39624,7550 +H123,east,tenant,2,0,68036,0,22348,16481 +H114,north,owner,2,2,69646,0,34265,16316 +H313,north,tenant,4,0,0,24132,10562,5033 +H093,south,tenant,1,3,61342,26289,36023,24457 +H368,south,owner,1,2,40107,0,10869,7936 +H373,south,tenant,2,2,38377,16448,15105,13418 +H192,north,tenant,2,0,30951,13265,10384,11749 +H133,north,owner,3,1,24839,0,40048,4558 +H091,north,tenant,3,1,45571,19531,30114,13239 +H372,north,tenant,3,0,102557,43953,22978,45178 +H188,north,owner,2,2,58982,0,6444,10756 +H199,north,tenant,2,2,77804,0,0,21363 +H108,north,owner,2,0,84082,36035,5062,36863 +H151,north,owner,2,0,14969,6415,2517,5224 +H003,east,owner,3,0,101041,0,4937,25835 diff --git a/tasks/price-index/price-index-income-distribution-d3-t0069/instruction.md b/tasks/price-index/price-index-income-distribution-d3-t0069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..043f8fa8fa09247a0e5e07ef53ac850543577830 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0069/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 50 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-t0069/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-t0069/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0069/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-t0069/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-t0069/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0069/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-income-distribution-d3-t0081/environment/Dockerfile b/tasks/price-index/price-index-income-distribution-d3-t0081/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0081/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-income-distribution-d3-t0081/environment/workdir/households.csv b/tasks/price-index/price-index-income-distribution-d3-t0081/environment/workdir/households.csv new file mode 100644 index 0000000000000000000000000000000000000000..2652248c12463cf3a538a86e8c35e3b6972be72f --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0081/environment/workdir/households.csv @@ -0,0 +1,36 @@ +household_id,region,tenure,members_14_or_over,children_under_14,wages,self_employment_income,pensions_and_benefits,taxes_paid +H058,west,owner,4,0,0,77646,56286,23150 +H146,north,tenant,2,2,100148,0,13106,33704 +H169,east,tenant,1,3,67882,0,0,14395 +H049,south,owner,1,2,66634,0,0,20688 +H132,north,owner,3,2,45875,0,1291,14114 +H014,east,owner,2,3,179476,0,9374,50544 +H121,north,owner,2,2,0,11205,23695,2313 +H024,west,owner,2,1,44726,0,32665,8129 +H366,south,tenant,2,0,80102,0,3378,24637 +H293,north,owner,2,0,125701,0,0,32839 +H016,south,tenant,3,1,99222,0,0,24340 +H396,east,tenant,1,2,71690,0,3125,13471 +H365,south,owner,1,0,30905,0,877,7852 +H192,north,tenant,2,3,0,30926,8687,7469 +H335,west,owner,2,3,132722,0,17526,42605 +H141,east,owner,3,1,0,97529,77514,18683 +H333,south,owner,4,0,0,161824,0,43321 +H071,west,tenant,2,2,68499,0,36598,21856 +H092,east,tenant,2,0,44163,0,20834,10828 +H126,west,owner,1,0,33162,0,3268,11014 +H392,east,tenant,1,0,32899,0,0,9065 +H205,west,owner,1,2,70469,0,39340,18198 +H188,north,owner,2,1,61736,0,53575,16349 +H034,north,owner,4,0,79231,0,3196,18534 +H165,west,owner,2,3,106332,0,0,32924 +H066,south,owner,4,2,235030,0,6854,43058 +H330,north,owner,1,2,15278,0,41879,3403 +H379,south,owner,2,3,70077,0,0,13613 +H040,east,owner,1,1,79290,0,2317,15505 +H300,east,owner,1,0,0,50770,12793,10163 +H140,south,tenant,1,2,70882,0,15977,15369 +H196,north,owner,3,3,32570,0,1150,8291 +H095,east,owner,2,0,38356,16438,28704,11408 +H127,west,owner,4,2,150835,0,11934,33562 +H061,south,tenant,1,0,0,79296,14677,26658 diff --git a/tasks/price-index/price-index-income-distribution-d3-t0081/instruction.md b/tasks/price-index/price-index-income-distribution-d3-t0081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..840d8e8359d7fb4aeaeba35a12a56aa4f9f3a573 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0081/instruction.md @@ -0,0 +1,28 @@ +# Income distribution from a household survey + +`households.csv` gives the annual income components and the composition of 35 households from a survey. Disposable income = `wages` + `self_employment_income` + `pensions_and_benefits` - `taxes_paid`. + +Work with **equivalised** income per **person**. A household's equivalence scale is 1.0 for the first member aged 14 or over, plus 0.5 for each further member aged 14 or over, plus 0.3 for each child under 14. Its equivalised income is its disposable income divided by that scale. Every member of the household, children included, is then one observation with the household's equivalised income: a household of four people counts four times. All the measures below are computed over persons (n = the number of persons). + +Gini coefficient: sort the incomes from lowest to highest and number them i = 1, 2, ..., n. Then + + G = 2 x sum(i x income_i) / (n x sum(income_i)) - (n + 1) / n + +Quintile shares: with the incomes sorted from lowest to highest, Q1 is the poorest fifth of the persons, Q5 the richest fifth (n is a multiple of 5, so each fifth holds exactly n / 5 persons). A quintile's share is its total income as a percentage of everyone's total income. S80/S20 is the total income of Q5 divided by the total income of Q1. + +Median: the middle value of the sorted incomes; with an even n, the mean of the two middle values. + +Write `answer.json` in this folder, a JSON object with: + +- `persons`: the number of persons, an integer. +- `mean_income` and `median_income`: of equivalised disposable income per person, 2 decimals. +- `gini`: the Gini coefficient, 4 decimals. +- `quintile_shares_percent`: object with keys `Q1` to `Q5`: each quintile's share of total income in per cent, 2 decimals. +- `s80_s20`: the income quintile share ratio, 2 decimals. +- `poverty_threshold`: 60% of the median income, 2 decimals. +- `persons_at_risk`: the number of persons with an income strictly below the threshold, an integer. +- `at_risk_of_poverty_rate_percent`: that number as a percentage of all persons, 2 decimals. +- `children_at_risk`: the number of children under 14 living in households below the threshold, an integer. +- `child_at_risk_rate_percent`: that number as a percentage of all children under 14, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-income-distribution-d3-t0081/solution/oracle.py b/tasks/price-index/price-index-income-distribution-d3-t0081/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0081/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-income-distribution-d3-t0081/tests/verify.py b/tasks/price-index/price-index-income-distribution-d3-t0081/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-income-distribution-d3-t0081/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..f46e6cff400c310995ce5f61be520e8781314a18 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2012-02,107.26 +Food,2012-03,108.23 +Housing,2012-02,101.32 +Housing,2012-03,99.76 +Transport services,2012-02,100.03 +Transport services,2012-03,102.92 +Communication,2012-02,105.02 +Communication,2012-03,113.64 +Furnishings,2012-02,102.67 +Furnishings,2012-03,110.46 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..7eb327db933de8ad3d575a39e1b7a4d182bcf8ee --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2012-03", + "comparison_month": "2012-02" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..8679f855ea2043ced1669735220fd9e1addc836e --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0002/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Transport services,125 +Food,306 +Housing,415 +Furnishings,94 +Communication,60 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0002/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-e0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1f5e7ab0e677ae0dcd5a944fa028304aca843454 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0002/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2012-03 (the current month) with 2012-02 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2012-02"` and `"2012-03"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2012-02 to 2012-03, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0002/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-e0002/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0002/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0002/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-e0002/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0002/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..9fcd6803f3385bf063218f814a3065bfe694ed12 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2018-08,100.48 +Food,2018-09,101.07 +Restaurants,2018-08,110.16 +Restaurants,2018-09,110.20 +Communication,2018-08,106.90 +Communication,2018-09,118.26 +Alcohol and tobacco,2018-08,110.84 +Alcohol and tobacco,2018-09,121.86 +Clothing,2018-08,100.27 +Clothing,2018-09,95.28 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..ee93c564601ae3d6726d428779c4219633eb2d68 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2018-09", + "comparison_month": "2018-08" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..7f0a868b7d24e37bf87817da6b4033fcd833f1ae --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0014/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Restaurants,227 +Food,349 +Clothing,175 +Alcohol and tobacco,140 +Communication,109 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0014/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-e0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ae80bf80624419765ca9fea8125b7b3035b722ab --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0014/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2018-09 (the current month) with 2018-08 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2018-08"` and `"2018-09"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2018-08 to 2018-09, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0014/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-e0014/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0014/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-e0014/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-e0014/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-e0014/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..46184610d8c18cd21b1797b920b8525d45efc4b4 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2018-06,104.49 +Food,2018-07,98.61 +Restaurants,2018-06,105.93 +Restaurants,2018-07,107.37 +Transport services,2018-06,111.05 +Transport services,2018-07,122.02 +Communication,2018-06,111.82 +Communication,2018-07,117.00 +Housing,2018-06,106.44 +Housing,2018-07,115.37 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..b7faf0d088551ff32dea15e393868a0baa8f80ed --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2018-07", + "comparison_month": "2018-06" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..4dab7c7236d118a9fe627909b84f5b2ed43a1e24 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0002/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Communication,45 +Housing,300 +Transport services,176 +Food,340 +Restaurants,139 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0002/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-t0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2aa0fa5aded7d61ac72f3414479e7398e9a5dac --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0002/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2018-07 (the current month) with 2018-06 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2018-06"` and `"2018-07"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2018-06 to 2018-07, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0002/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-t0002/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0002/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0002/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-t0002/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0002/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..7d8ae396b22f0cf32bbce1fac30247f18570a2c5 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2019-12,109.10 +Food,2020-01,116.93 +Communication,2019-12,111.72 +Communication,2020-01,124.75 +Motor fuels,2019-12,107.81 +Motor fuels,2020-01,70.35 +Transport services,2019-12,107.85 +Transport services,2020-01,112.26 +Health,2019-12,107.14 +Health,2020-01,113.85 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..365312a783ea441be135fc8eda14af80d8a7ab31 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2020-01", + "comparison_month": "2019-12" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..fd57168182e8ef283ee4bba0bd3dd4c0392bb703 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0014/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Food,399 +Communication,92 +Transport services,280 +Health,116 +Motor fuels,113 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0014/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-t0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e5b279c506752831fae6699f83c3e9f8368ce6e --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0014/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2020-01 (the current month) with 2019-12 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2019-12"` and `"2020-01"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2019-12 to 2020-01, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0014/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-t0014/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0014/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0014/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-t0014/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0014/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..3434978bad18542ab5a1807e4abf56dbc44cfe98 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2018-09,105.76 +Food,2018-10,122.11 +Electricity and gas,2018-09,109.57 +Electricity and gas,2018-10,108.00 +Restaurants,2018-09,109.58 +Restaurants,2018-10,112.07 +Clothing,2018-09,101.79 +Clothing,2018-10,111.45 +Communication,2018-09,104.11 +Communication,2018-10,106.35 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..16adb1d5d799dd35f5a677a38c8b7dd383d59d2b --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2018-10", + "comparison_month": "2018-09" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..687233598f4d571850037c39707d7f2aa004c773 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0026/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Restaurants,246 +Electricity and gas,209 +Clothing,140 +Food,317 +Communication,88 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0026/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-t0026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82315a271ca8da3aa417d158f78894765529f425 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0026/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2018-10 (the current month) with 2018-09 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2018-09"` and `"2018-10"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2018-09 to 2018-10, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0026/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-t0026/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0026/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0026/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-t0026/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0026/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..0d25a7dc1f920596c460cc25518c4e0da496af39 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2016-01,108.23 +Food,2016-02,107.73 +Communication,2016-01,100.69 +Communication,2016-02,101.14 +Motor fuels,2016-01,100.20 +Motor fuels,2016-02,109.11 +Transport services,2016-01,103.53 +Transport services,2016-02,105.75 +Clothing,2016-01,103.81 +Clothing,2016-02,115.60 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..f5b9fc0e710c69eda3d334890ac518484a37cea8 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2016-02", + "comparison_month": "2016-01" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..a6ca0ce4fa426e0c3380d1a1cf0f7b42f1f9bbe2 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0038/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Transport services,224 +Clothing,148 +Communication,85 +Food,390 +Motor fuels,153 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0038/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-t0038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..461a19fb849db4f78c1acba6ec027621f2290343 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0038/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2016-02 (the current month) with 2016-01 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2016-01"` and `"2016-02"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2016-01 to 2016-02, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0038/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-t0038/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0038/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0038/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-t0038/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0038/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..f2b730ff396402a7f89ae211337d1d9038376563 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2021-04,109.20 +Food,2021-05,105.08 +Communication,2021-04,106.47 +Communication,2021-05,109.33 +Recreation,2021-04,103.40 +Recreation,2021-05,106.91 +Restaurants,2021-04,104.92 +Restaurants,2021-05,111.78 +Electricity and gas,2021-04,108.85 +Electricity and gas,2021-05,92.36 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..00dbd53de968621c06c6d8b9db0617f6032ff86b --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2021-05", + "comparison_month": "2021-04" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..7fa396f7d3263936a6fb18de54be4d6c4404345b --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0050/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Food,400 +Communication,84 +Restaurants,124 +Electricity and gas,138 +Recreation,254 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0050/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-t0050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..550179d2d4d1e40dca83498cdb679af84c59b418 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0050/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2021-05 (the current month) with 2021-04 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2021-04"` and `"2021-05"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2021-04 to 2021-05, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0050/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-t0050/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0050/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0050/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-t0050/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0050/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..e4cd75c2c26cdb60cca1f49167ded6d27112294a --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2020-05,106.77 +Food,2020-06,115.86 +Alcohol and tobacco,2020-05,111.01 +Alcohol and tobacco,2020-06,113.72 +Electricity and gas,2020-05,100.08 +Electricity and gas,2020-06,95.83 +Housing,2020-05,110.51 +Housing,2020-06,112.37 +Clothing,2020-05,110.67 +Clothing,2020-06,107.72 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..cdf098f28241c6c28ba425dfd459450a1699f547 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2020-06", + "comparison_month": "2020-05" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..42998ce8436ed353de5523515564485b2fb85aa5 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0062/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Food,217 +Alcohol and tobacco,72 +Housing,512 +Clothing,96 +Electricity and gas,103 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0062/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-t0062/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0348bcbe8e82324d82fef13c14c9e681ee140920 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0062/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2020-06 (the current month) with 2020-05 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2020-05"` and `"2020-06"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2020-05 to 2020-06, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0062/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-t0062/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0062/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0062/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-t0062/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0062/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..9e21f4fce52ae039ec02292898f09caa7a36b5e6 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/indices.csv @@ -0,0 +1,11 @@ +category,month,index +Food,2014-07,110.20 +Food,2014-08,107.03 +Motor fuels,2014-07,107.08 +Motor fuels,2014-08,102.00 +Communication,2014-07,105.70 +Communication,2014-08,110.06 +Electricity and gas,2014-07,102.93 +Electricity and gas,2014-08,96.41 +Health,2014-07,101.94 +Health,2014-08,101.63 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..639b99de858c74d2ef99bbaf13d1ffdd73c0c220 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2014-08", + "comparison_month": "2014-07" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..e9018f4b2a3787506e20e76855043fbb5447ef84 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0074/environment/workdir/weights.csv @@ -0,0 +1,6 @@ +category,weight +Electricity and gas,149 +Communication,92 +Food,487 +Motor fuels,114 +Health,158 diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0074/instruction.md b/tasks/price-index/price-index-inflation-contributions-d1-t0074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b79c4c57a8e55b39c01392cb518b1610e1ef5bc2 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0074/instruction.md @@ -0,0 +1,18 @@ +# Contributions to inflation + +`weights.csv` gives the weight of each category in parts per thousand. `indices.csv` gives each category's price index in two months. Every category's index equals 100 in the period the weights refer to. + +Compare 2014-08 (the current month) with 2014-07 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2014-07"` and `"2014-08"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2014-07 to 2014-08, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0074/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d1-t0074/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0074/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d1-t0074/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d1-t0074/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d1-t0074/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..3e85c177c4b23fe23715d3675043feaaa2156b3f --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/indices.csv @@ -0,0 +1,121 @@ +category,month,index +Electricity and gas,2023-04,111.69 +Health,2023-05,101.68 +Furnishings,2023-06,104.39 +Food,2022-09,111.82 +Electricity and gas,2023-01,115.36 +Food,2022-11,113.69 +Clothing,2023-04,117.82 +Communication,2022-10,106.09 +Communication,2023-06,106.47 +Food,2023-03,120.36 +Health,2022-10,106.06 +Furnishings,2023-07,106.20 +Electricity and gas,2023-02,112.50 +Electricity and gas,2023-05,113.73 +Clothing,2022-07,107.61 +Clothing,2023-05,119.12 +Health,2023-09,103.73 +Housing,2022-11,111.45 +Food,2023-07,127.09 +Communication,2023-07,106.09 +Communication,2023-05,105.65 +Furnishings,2022-08,101.28 +Housing,2023-02,114.45 +Communication,2023-08,106.38 +Motor fuels,2023-09,115.18 +Furnishings,2022-09,102.09 +Motor fuels,2022-07,100.81 +Health,2023-01,104.84 +Clothing,2022-10,110.75 +Housing,2023-05,119.34 +Electricity and gas,2022-10,109.04 +Communication,2022-08,105.15 +Food,2023-05,124.52 +Communication,2022-09,106.41 +Electricity and gas,2023-07,112.57 +Food,2023-04,123.07 +Clothing,2022-08,108.44 +Food,2023-06,126.05 +Housing,2022-09,109.89 +Housing,2022-12,111.98 +Furnishings,2023-02,102.71 +Communication,2023-02,104.57 +Motor fuels,2023-02,111.81 +Housing,2022-10,110.48 +Food,2022-12,113.49 +Health,2022-09,106.56 +Clothing,2023-01,113.57 +Health,2022-12,105.23 +Communication,2023-03,104.29 +Communication,2022-07,104.54 +Food,2023-09,129.50 +Motor fuels,2023-06,108.39 +Communication,2023-04,105.24 +Health,2022-08,107.63 +Communication,2023-09,107.04 +Electricity and gas,2023-06,117.88 +Furnishings,2023-05,102.29 +Motor fuels,2022-10,104.24 +Motor fuels,2023-04,109.23 +Clothing,2022-11,111.23 +Motor fuels,2022-11,105.91 +Furnishings,2022-12,101.91 +Electricity and gas,2022-11,104.83 +Health,2022-07,108.46 +Clothing,2023-06,119.74 +Housing,2023-08,123.08 +Motor fuels,2022-09,105.38 +Motor fuels,2022-08,99.37 +Housing,2023-03,115.91 +Clothing,2023-03,115.77 +Clothing,2023-08,123.05 +Health,2022-11,105.85 +Food,2022-07,108.17 +Electricity and gas,2023-03,109.02 +Furnishings,2022-07,101.06 +Communication,2022-12,105.20 +Housing,2023-04,117.46 +Clothing,2023-07,121.61 +Health,2023-06,101.72 +Food,2022-10,111.74 +Motor fuels,2023-07,109.61 +Electricity and gas,2022-12,111.38 +Clothing,2022-09,108.92 +Health,2023-02,104.25 +Motor fuels,2023-05,113.66 +Clothing,2022-12,111.79 +Electricity and gas,2023-09,107.46 +Communication,2022-11,105.66 +Housing,2022-08,108.68 +Furnishings,2023-09,106.60 +Food,2023-01,116.33 +Motor fuels,2023-08,113.48 +Housing,2022-07,107.07 +Furnishings,2023-04,102.75 +Furnishings,2022-11,102.50 +Clothing,2023-09,123.07 +Furnishings,2023-08,106.93 +Furnishings,2022-10,101.88 +Communication,2023-01,104.87 +Housing,2023-09,123.54 +Clothing,2023-02,115.28 +Electricity and gas,2022-08,103.11 +Health,2023-04,103.04 +Furnishings,2023-03,102.69 +Housing,2023-01,112.90 +Furnishings,2023-01,102.76 +Health,2023-08,103.32 +Food,2023-08,128.54 +Food,2023-02,117.19 +Motor fuels,2023-03,108.61 +Housing,2023-06,121.36 +Electricity and gas,2023-08,107.60 +Food,2022-08,109.66 +Motor fuels,2022-12,103.09 +Motor fuels,2023-01,101.25 +Electricity and gas,2022-07,101.93 +Health,2023-03,103.53 +Health,2023-07,103.21 +Electricity and gas,2022-09,102.06 +Housing,2023-07,122.23 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..bc831f34640b484e39fcc42921eaa0bb4bc817be --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2023-07", + "comparison_month": "2022-07" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..504df8db30174b69f7cd041bffa95d2c7f3fbe90 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0006/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Health,1124.3 +Electricity and gas,1489.6 +Furnishings,1491.0 +Motor fuels,1250.7 +Food,4263.5 +Housing,4682.8 +Clothing,1027.6 +Communication,696.9 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0006/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-e0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4c8b9576359b299f185f6e5e8219960bccc5b38 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0006/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2023-07 (the current month) with 2022-07 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2022-07"` and `"2023-07"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2022-07 to 2023-07, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0006/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-e0006/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0006/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0006/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-e0006/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0006/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..476c182a1c3fe1958c158710dde2abcff0ecb3c8 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/indices.csv @@ -0,0 +1,153 @@ +category,month,index +Restaurants,2013-02,108.41 +Health,2013-12,95.73 +Health,2013-05,98.35 +Restaurants,2013-12,114.30 +Food,2012-10,109.41 +Transport services,2012-10,101.35 +Communication,2013-10,113.84 +Communication,2013-08,111.95 +Restaurants,2013-08,111.84 +Transport services,2014-04,95.66 +Transport services,2013-03,100.84 +Health,2012-11,101.06 +Restaurants,2013-09,112.04 +Restaurants,2012-11,105.56 +Motor fuels,2014-02,105.99 +Communication,2013-03,108.43 +Food,2013-07,112.82 +Food,2014-03,122.41 +Transport services,2012-12,100.58 +Furnishings,2013-12,112.09 +Health,2012-10,102.17 +Food,2014-04,123.76 +Clothing,2013-04,111.08 +Clothing,2013-12,115.37 +Clothing,2013-08,114.70 +Restaurants,2014-03,116.54 +Motor fuels,2012-10,104.12 +Communication,2014-04,120.13 +Health,2013-01,100.23 +Communication,2012-12,108.02 +Restaurants,2013-06,110.27 +Furnishings,2013-02,109.29 +Transport services,2014-01,96.04 +Furnishings,2013-08,112.05 +Communication,2013-11,114.40 +Clothing,2014-03,117.05 +Restaurants,2013-01,107.03 +Food,2013-04,109.42 +Furnishings,2013-03,109.13 +Food,2013-02,107.30 +Transport services,2013-05,100.31 +Clothing,2013-01,108.87 +Communication,2013-12,116.86 +Food,2013-01,108.52 +Health,2012-12,101.65 +Communication,2012-11,107.46 +Communication,2013-09,112.85 +Clothing,2014-01,115.98 +Health,2013-09,97.23 +Clothing,2012-12,107.89 +Food,2013-05,110.82 +Communication,2014-02,118.86 +Restaurants,2013-11,113.73 +Restaurants,2013-04,109.31 +Furnishings,2013-07,111.79 +Transport services,2013-01,101.23 +Restaurants,2013-05,109.82 +Motor fuels,2013-03,107.72 +Clothing,2013-07,113.68 +Motor fuels,2013-05,106.63 +Motor fuels,2014-03,107.80 +Food,2013-11,117.20 +Health,2013-04,99.20 +Clothing,2013-09,114.30 +Communication,2013-06,111.22 +Motor fuels,2014-04,107.20 +Motor fuels,2013-07,104.28 +Communication,2013-01,109.48 +Health,2014-04,95.39 +Transport services,2013-10,98.21 +Restaurants,2012-12,105.91 +Clothing,2013-11,115.38 +Motor fuels,2013-06,103.07 +Motor fuels,2013-02,109.47 +Food,2013-03,108.30 +Communication,2014-03,119.17 +Health,2014-02,95.40 +Transport services,2013-04,100.56 +Health,2013-03,99.38 +Health,2013-11,95.51 +Motor fuels,2012-11,104.07 +Furnishings,2013-01,108.71 +Health,2013-10,96.64 +Motor fuels,2012-12,105.95 +Food,2014-01,118.32 +Restaurants,2014-04,116.83 +Communication,2012-10,106.87 +Food,2013-08,113.28 +Health,2014-01,96.07 +Health,2014-03,95.58 +Communication,2013-05,110.61 +Health,2013-07,97.47 +Transport services,2013-11,98.12 +Clothing,2013-03,110.02 +Transport services,2014-02,95.45 +Food,2013-10,114.43 +Communication,2014-01,118.04 +Clothing,2013-10,114.48 +Clothing,2014-02,117.52 +Restaurants,2013-07,111.46 +Transport services,2013-07,100.41 +Food,2013-06,111.39 +Motor fuels,2013-08,100.61 +Furnishings,2014-04,115.50 +Furnishings,2013-05,111.07 +Furnishings,2013-10,111.77 +Restaurants,2014-01,115.03 +Motor fuels,2013-04,110.43 +Communication,2013-02,110.31 +Furnishings,2012-11,108.14 +Motor fuels,2013-12,100.54 +Food,2013-12,119.53 +Health,2013-08,97.13 +Furnishings,2012-12,108.17 +Motor fuels,2013-10,103.91 +Restaurants,2014-02,116.30 +Food,2014-02,120.95 +Health,2013-02,99.36 +Furnishings,2014-01,112.68 +Clothing,2013-02,110.42 +Transport services,2013-02,101.26 +Communication,2013-04,109.69 +Restaurants,2013-10,113.36 +Motor fuels,2013-09,98.60 +Motor fuels,2013-11,104.35 +Furnishings,2013-09,112.02 +Restaurants,2013-03,108.61 +Transport services,2013-06,100.73 +Furnishings,2013-06,111.48 +Furnishings,2014-02,114.00 +Furnishings,2012-10,107.87 +Transport services,2013-09,99.03 +Furnishings,2014-03,114.96 +Clothing,2012-11,107.04 +Transport services,2014-03,95.23 +Transport services,2013-12,97.68 +Clothing,2014-04,117.49 +Furnishings,2013-04,109.92 +Transport services,2012-11,100.68 +Food,2013-09,115.26 +Clothing,2013-06,112.98 +Transport services,2013-08,98.99 +Restaurants,2012-10,105.47 +Motor fuels,2014-01,103.49 +Food,2012-11,108.69 +Communication,2013-07,111.19 +Furnishings,2013-11,111.46 +Health,2013-06,97.68 +Food,2012-12,108.42 +Clothing,2013-05,111.76 +Clothing,2012-10,106.50 +Motor fuels,2013-01,109.79 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..1fc9cb4756c77703f02d1aa432cacfff1aede89b --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2014-02", + "comparison_month": "2013-02" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..89e068f61642454072bc454860dd75424a4133c0 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0018/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Furnishings,510.3 +Clothing,532.5 +Motor fuels,533.1 +Health,632.8 +Communication,289.1 +Transport services,1011.9 +Restaurants,924.4 +Food,1856.2 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0018/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-e0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..771ae422d87d82c89df3dab65be3fbc07c0b42cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0018/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2014-02 (the current month) with 2013-02 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2013-02"` and `"2014-02"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2013-02 to 2014-02, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0018/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-e0018/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0018/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-e0018/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-e0018/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-e0018/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..ead3156417dcd3e1e2e0e59464da60fb8ae794c5 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/indices.csv @@ -0,0 +1,121 @@ +category,month,index +Motor fuels,2017-07,98.32 +Alcohol and tobacco,2017-06,106.40 +Motor fuels,2017-12,104.14 +Communication,2018-04,117.35 +Housing,2017-05,104.47 +Housing,2018-01,106.84 +Alcohol and tobacco,2018-04,120.18 +Housing,2017-11,107.13 +Health,2018-03,108.40 +Housing,2018-02,108.44 +Communication,2017-11,114.48 +Housing,2017-08,106.79 +Alcohol and tobacco,2017-11,113.34 +Housing,2017-04,105.85 +Food,2017-04,104.01 +Communication,2018-02,117.62 +Food,2017-12,104.92 +Food,2018-04,103.51 +Food,2017-07,103.92 +Food,2017-08,104.17 +Restaurants,2017-06,110.53 +Communication,2017-12,115.92 +Housing,2017-09,107.35 +Communication,2018-03,117.88 +Health,2017-04,108.22 +Alcohol and tobacco,2017-09,111.12 +Health,2017-07,109.07 +Motor fuels,2018-04,106.83 +Alcohol and tobacco,2017-08,108.91 +Motor fuels,2017-06,99.39 +Health,2017-12,108.53 +Transport services,2018-03,103.24 +Communication,2017-10,113.34 +Restaurants,2017-10,112.89 +Restaurants,2017-04,108.20 +Transport services,2017-07,103.89 +Communication,2017-09,111.92 +Restaurants,2018-02,114.51 +Transport services,2018-01,102.94 +Alcohol and tobacco,2017-07,107.65 +Food,2018-01,103.83 +Food,2017-11,104.01 +Restaurants,2017-07,110.42 +Food,2018-05,103.35 +Alcohol and tobacco,2018-06,122.42 +Motor fuels,2017-10,102.79 +Transport services,2017-08,104.27 +Health,2017-11,108.50 +Motor fuels,2018-02,101.49 +Housing,2017-12,107.58 +Food,2018-06,102.17 +Housing,2017-06,105.22 +Housing,2018-05,109.40 +Communication,2017-06,109.10 +Alcohol and tobacco,2018-03,118.80 +Health,2018-02,108.00 +Food,2018-02,103.57 +Health,2017-10,108.93 +Restaurants,2018-06,118.23 +Health,2017-09,108.23 +Transport services,2018-02,103.14 +Health,2018-04,108.05 +Restaurants,2017-05,109.33 +Restaurants,2018-01,113.89 +Food,2017-10,104.46 +Restaurants,2017-12,112.46 +Alcohol and tobacco,2017-05,105.56 +Transport services,2018-04,103.71 +Food,2017-06,101.76 +Housing,2017-07,106.86 +Communication,2018-06,119.70 +Communication,2017-08,110.38 +Transport services,2017-06,103.97 +Food,2018-03,103.37 +Motor fuels,2017-09,100.19 +Motor fuels,2017-04,106.98 +Alcohol and tobacco,2018-01,116.88 +Housing,2017-10,107.98 +Motor fuels,2017-11,102.15 +Alcohol and tobacco,2018-02,118.00 +Health,2017-05,108.49 +Transport services,2018-06,103.39 +Motor fuels,2018-03,103.19 +Communication,2017-07,108.97 +Health,2018-01,109.29 +Health,2018-05,107.49 +Health,2017-08,108.24 +Restaurants,2017-11,112.71 +Restaurants,2017-09,112.68 +Alcohol and tobacco,2018-05,121.91 +Motor fuels,2017-08,100.02 +Transport services,2017-05,104.57 +Restaurants,2018-03,115.06 +Restaurants,2017-08,111.70 +Transport services,2017-12,102.86 +Motor fuels,2018-01,99.12 +Food,2017-09,104.60 +Transport services,2017-10,104.19 +Transport services,2018-05,103.94 +Communication,2017-05,107.78 +Motor fuels,2017-05,102.15 +Alcohol and tobacco,2017-04,103.66 +Restaurants,2018-05,116.35 +Transport services,2017-11,103.54 +Transport services,2017-09,106.05 +Communication,2018-05,118.84 +Alcohol and tobacco,2017-12,114.62 +Housing,2018-03,108.87 +Health,2018-06,108.18 +Communication,2018-01,117.38 +Restaurants,2018-04,115.73 +Motor fuels,2018-06,117.64 +Housing,2018-06,109.77 +Health,2017-06,108.09 +Alcohol and tobacco,2017-10,112.42 +Transport services,2017-04,105.09 +Food,2017-05,102.81 +Communication,2017-04,107.79 +Motor fuels,2018-05,113.48 +Housing,2018-04,109.83 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..545a00a34cf7a02d31d84f6beb1de544a5f04e42 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2018-06", + "comparison_month": "2017-06" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..7c311e543e5c05f19d5b92a40d501492c5913f25 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0006/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Communication,411.3 +Health,615.4 +Transport services,850.8 +Food,2169.1 +Housing,3047.2 +Motor fuels,645.8 +Alcohol and tobacco,361.4 +Restaurants,822.5 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0006/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-t0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a321652d444515f2fd2c0d97609d6fdb181f20d6 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0006/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2018-06 (the current month) with 2017-06 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2017-06"` and `"2018-06"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2017-06 to 2018-06, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0006/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-t0006/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0006/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0006/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-t0006/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0006/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..1fbb801fd6669ffcb979a176908715cd91a789ab --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/indices.csv @@ -0,0 +1,121 @@ +category,month,index +Clothing,2013-09,106.59 +Housing,2014-03,112.31 +Housing,2014-04,111.53 +Housing,2013-04,102.25 +Recreation,2014-01,104.63 +Restaurants,2014-01,109.85 +Recreation,2013-09,106.40 +Food,2013-11,105.57 +Recreation,2014-04,103.50 +Electricity and gas,2013-07,111.13 +Restaurants,2013-06,105.75 +Recreation,2013-08,107.22 +Recreation,2013-12,105.44 +Clothing,2014-03,107.01 +Transport services,2014-02,102.58 +Alcohol and tobacco,2013-12,114.60 +Transport services,2013-12,102.29 +Alcohol and tobacco,2013-04,110.08 +Alcohol and tobacco,2013-06,111.40 +Clothing,2014-01,106.79 +Food,2014-03,102.86 +Clothing,2013-08,106.73 +Transport services,2013-09,103.34 +Recreation,2013-11,105.20 +Transport services,2014-03,102.85 +Recreation,2013-07,107.50 +Alcohol and tobacco,2013-03,109.96 +Clothing,2013-05,105.67 +Electricity and gas,2013-09,114.72 +Housing,2014-01,110.49 +Recreation,2013-04,105.37 +Alcohol and tobacco,2014-01,115.90 +Electricity and gas,2013-06,110.91 +Food,2013-06,104.74 +Housing,2013-03,101.21 +Electricity and gas,2013-12,102.39 +Housing,2013-09,106.97 +Electricity and gas,2014-03,108.02 +Recreation,2013-06,106.20 +Restaurants,2014-04,110.06 +Restaurants,2013-12,108.26 +Electricity and gas,2013-03,103.52 +Food,2013-07,106.36 +Transport services,2014-04,104.04 +Clothing,2014-02,107.09 +Electricity and gas,2013-10,110.58 +Recreation,2014-02,104.04 +Clothing,2013-02,104.83 +Housing,2013-07,105.78 +Transport services,2014-01,102.16 +Alcohol and tobacco,2013-11,113.97 +Alcohol and tobacco,2014-02,114.87 +Food,2013-12,104.36 +Clothing,2014-04,108.21 +Food,2014-01,102.84 +Food,2013-02,109.99 +Transport services,2013-11,102.75 +Alcohol and tobacco,2014-04,116.29 +Recreation,2013-05,105.09 +Clothing,2013-03,105.59 +Electricity and gas,2013-05,104.70 +Housing,2013-05,103.46 +Transport services,2013-04,102.54 +Clothing,2013-06,106.81 +Electricity and gas,2014-04,102.11 +Food,2013-05,105.50 +Food,2013-08,106.12 +Restaurants,2013-08,106.11 +Recreation,2013-10,105.36 +Restaurants,2013-09,106.58 +Housing,2013-10,108.28 +Transport services,2013-10,102.26 +Alcohol and tobacco,2014-03,115.46 +Housing,2013-11,108.17 +Transport services,2013-05,102.46 +Housing,2013-06,104.26 +Housing,2014-02,111.73 +Recreation,2014-03,103.37 +Restaurants,2013-03,106.71 +Restaurants,2013-04,106.17 +Clothing,2013-10,106.69 +Recreation,2013-02,105.82 +Food,2013-10,105.56 +Housing,2013-12,108.47 +Transport services,2013-08,103.12 +Electricity and gas,2014-01,104.63 +Restaurants,2014-03,110.65 +Food,2013-03,108.01 +Food,2013-09,105.62 +Transport services,2013-03,101.28 +Transport services,2013-06,103.08 +Electricity and gas,2013-02,104.03 +Clothing,2013-07,107.45 +Restaurants,2013-02,107.03 +Electricity and gas,2013-11,108.75 +Restaurants,2013-05,106.07 +Restaurants,2014-02,110.30 +Transport services,2013-07,102.98 +Clothing,2013-04,106.06 +Alcohol and tobacco,2013-10,113.81 +Restaurants,2013-11,107.54 +Food,2014-02,102.67 +Housing,2013-08,106.60 +Restaurants,2013-10,106.56 +Restaurants,2013-07,105.85 +Electricity and gas,2013-04,100.09 +Alcohol and tobacco,2013-07,111.87 +Alcohol and tobacco,2013-05,110.84 +Electricity and gas,2013-08,110.87 +Housing,2013-02,100.38 +Food,2013-04,107.11 +Transport services,2013-02,101.16 +Alcohol and tobacco,2013-09,112.84 +Food,2014-04,101.75 +Electricity and gas,2014-02,104.08 +Alcohol and tobacco,2013-02,109.04 +Alcohol and tobacco,2013-08,112.20 +Recreation,2013-03,106.15 +Clothing,2013-12,106.66 +Clothing,2013-11,107.35 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..3eb66c6e4492de5a0b8bc46aef309ddaccf4c3c6 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2014-03", + "comparison_month": "2013-03" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..38835227ee4b0132e73436fba1905b2acc50d242 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0018/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Food,5411.7 +Restaurants,2042.8 +Recreation,3781.5 +Alcohol and tobacco,1241.2 +Electricity and gas,1728.6 +Housing,6911.1 +Transport services,1959.3 +Clothing,2124.9 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0018/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-t0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..98a65c2b18c839fa4b9c2a194c0dbe19c37ab1e4 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0018/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2014-03 (the current month) with 2013-03 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2013-03"` and `"2014-03"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2013-03 to 2014-03, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0018/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-t0018/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0018/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0018/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-t0018/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0018/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..a57967ac092dfd14619e915b03c7ccdc3561c6cb --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/indices.csv @@ -0,0 +1,145 @@ +category,month,index +Alcohol and tobacco,2024-02,109.09 +Housing,2023-10,119.29 +Alcohol and tobacco,2023-12,107.96 +Recreation,2024-01,116.55 +Clothing,2023-07,107.71 +Housing,2023-09,118.34 +Restaurants,2024-03,111.61 +Electricity and gas,2024-03,125.04 +Motor fuels,2023-05,95.09 +Food,2024-03,114.56 +Electricity and gas,2023-04,113.78 +Motor fuels,2023-02,106.78 +Clothing,2023-10,107.86 +Motor fuels,2024-02,88.65 +Recreation,2023-01,106.16 +Recreation,2023-06,110.74 +Electricity and gas,2023-11,115.28 +Clothing,2023-12,109.37 +Food,2022-12,109.42 +Food,2022-11,109.55 +Recreation,2023-03,107.06 +Housing,2023-06,117.42 +Electricity and gas,2023-05,117.83 +Housing,2023-04,115.57 +Clothing,2023-11,107.98 +Food,2023-06,109.00 +Motor fuels,2023-06,90.99 +Motor fuels,2022-11,103.39 +Electricity and gas,2023-09,120.47 +Alcohol and tobacco,2023-11,108.03 +Recreation,2023-08,112.36 +Housing,2022-11,109.88 +Restaurants,2024-02,111.46 +Alcohol and tobacco,2023-02,106.48 +Restaurants,2024-01,111.97 +Restaurants,2023-06,109.34 +Food,2024-02,111.47 +Housing,2023-07,117.06 +Food,2023-08,107.93 +Food,2023-02,112.04 +Restaurants,2023-10,110.54 +Motor fuels,2023-04,98.67 +Restaurants,2023-02,108.07 +Clothing,2022-12,103.79 +Electricity and gas,2023-10,116.61 +Restaurants,2023-08,109.00 +Alcohol and tobacco,2024-04,108.49 +Alcohol and tobacco,2024-01,108.88 +Electricity and gas,2023-06,123.16 +Restaurants,2023-11,110.98 +Recreation,2024-04,119.18 +Electricity and gas,2024-02,126.46 +Clothing,2024-04,110.15 +Housing,2023-08,117.91 +Housing,2023-03,114.35 +Electricity and gas,2023-08,124.34 +Recreation,2023-05,109.65 +Clothing,2023-08,108.32 +Electricity and gas,2023-03,111.21 +Motor fuels,2023-10,87.05 +Restaurants,2023-04,110.05 +Food,2023-11,110.70 +Alcohol and tobacco,2023-06,106.38 +Clothing,2023-09,107.99 +Alcohol and tobacco,2023-01,106.11 +Food,2023-05,109.90 +Food,2023-04,110.52 +Housing,2023-12,119.25 +Recreation,2023-09,112.49 +Motor fuels,2023-01,108.04 +Alcohol and tobacco,2023-07,105.54 +Recreation,2024-03,117.80 +Housing,2023-05,116.60 +Recreation,2023-04,108.04 +Food,2023-10,111.15 +Food,2023-07,108.32 +Alcohol and tobacco,2023-09,106.56 +Alcohol and tobacco,2024-03,108.85 +Motor fuels,2024-03,91.88 +Housing,2024-01,119.91 +Housing,2024-04,120.64 +Electricity and gas,2022-11,108.05 +Electricity and gas,2023-01,106.01 +Restaurants,2023-01,107.37 +Motor fuels,2023-12,84.01 +Food,2024-01,111.25 +Alcohol and tobacco,2022-12,105.68 +Clothing,2023-05,106.45 +Clothing,2024-02,109.55 +Electricity and gas,2024-01,120.63 +Motor fuels,2023-08,92.74 +Restaurants,2023-09,109.83 +Recreation,2022-11,104.04 +Clothing,2023-02,105.15 +Recreation,2024-02,116.37 +Motor fuels,2023-09,88.24 +Housing,2023-11,120.13 +Recreation,2023-11,114.69 +Motor fuels,2022-12,111.63 +Restaurants,2022-11,106.03 +Clothing,2023-04,105.55 +Restaurants,2022-12,107.71 +Food,2023-03,110.92 +Restaurants,2023-05,110.28 +Electricity and gas,2024-04,122.11 +Motor fuels,2024-01,84.95 +Alcohol and tobacco,2023-08,106.04 +Alcohol and tobacco,2023-04,105.82 +Clothing,2024-03,109.54 +Food,2024-04,111.33 +Clothing,2023-06,106.59 +Recreation,2023-02,107.08 +Motor fuels,2023-11,88.23 +Housing,2023-02,112.35 +Electricity and gas,2022-12,108.73 +Alcohol and tobacco,2022-11,104.40 +Housing,2022-12,111.49 +Recreation,2023-12,116.14 +Recreation,2022-12,105.07 +Food,2023-09,109.17 +Housing,2024-03,120.07 +Recreation,2023-07,111.18 +Food,2023-12,110.12 +Restaurants,2023-03,109.41 +Housing,2024-02,119.33 +Restaurants,2023-12,111.48 +Motor fuels,2023-03,103.73 +Motor fuels,2023-07,89.95 +Restaurants,2023-07,110.29 +Alcohol and tobacco,2023-03,106.48 +Motor fuels,2024-04,93.90 +Clothing,2024-01,109.84 +Clothing,2022-11,103.10 +Restaurants,2024-04,112.98 +Electricity and gas,2023-07,124.28 +Clothing,2023-01,104.19 +Clothing,2023-03,105.56 +Electricity and gas,2023-12,125.55 +Alcohol and tobacco,2023-05,106.08 +Housing,2023-01,112.47 +Recreation,2023-10,113.14 +Alcohol and tobacco,2023-10,106.67 +Electricity and gas,2023-02,108.29 +Food,2023-01,110.30 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..dc8f1dafea6e081888d24e69fd7d85db8b16445c --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2024-04", + "comparison_month": "2023-04" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..b3c2b4e15fed58810a8d335cbf833bead9889126 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0030/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Housing,2841.6 +Alcohol and tobacco,339.1 +Motor fuels,489.9 +Electricity and gas,822.6 +Clothing,596.9 +Food,1196.4 +Restaurants,687.8 +Recreation,1505.6 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0030/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-t0030/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41758e2eafe4cd47f1570e249c0e46eb508c96d8 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0030/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2024-04 (the current month) with 2023-04 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2023-04"` and `"2024-04"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2023-04 to 2024-04, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0030/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-t0030/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0030/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0030/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-t0030/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0030/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..495b78b4e0a1f2ec988710e7965b93c8793962c5 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/indices.csv @@ -0,0 +1,121 @@ +category,month,index +Communication,2012-01,111.51 +Clothing,2012-11,119.76 +Recreation,2012-09,111.40 +Food,2012-07,113.87 +Recreation,2013-03,114.88 +Motor fuels,2012-05,107.27 +Health,2012-11,107.56 +Food,2012-08,115.53 +Health,2013-03,107.42 +Furnishings,2013-03,118.66 +Communication,2013-03,115.42 +Food,2013-01,123.92 +Communication,2012-09,112.94 +Health,2012-10,107.35 +Transport services,2012-11,99.45 +Transport services,2012-12,98.38 +Transport services,2012-09,99.69 +Communication,2013-02,114.48 +Motor fuels,2012-10,115.24 +Transport services,2012-02,101.30 +Food,2012-02,109.35 +Health,2012-07,108.75 +Recreation,2012-02,108.91 +Health,2012-05,108.67 +Health,2012-02,108.87 +Motor fuels,2012-04,104.29 +Motor fuels,2013-03,105.46 +Motor fuels,2012-02,103.20 +Furnishings,2012-02,111.43 +Clothing,2013-03,121.46 +Food,2012-10,118.55 +Clothing,2013-02,121.55 +Clothing,2012-10,120.00 +Transport services,2012-04,101.21 +Food,2013-03,124.77 +Motor fuels,2012-07,108.23 +Motor fuels,2012-09,116.57 +Recreation,2012-12,112.84 +Recreation,2012-06,109.90 +Health,2013-02,107.31 +Recreation,2012-05,109.05 +Furnishings,2012-08,113.70 +Communication,2012-12,114.82 +Furnishings,2012-06,113.07 +Communication,2012-11,114.26 +Transport services,2012-07,100.01 +Recreation,2013-02,114.54 +Furnishings,2012-03,113.53 +Communication,2012-07,112.22 +Health,2012-09,108.36 +Food,2013-02,125.09 +Health,2012-12,107.34 +Clothing,2012-02,112.71 +Clothing,2012-07,116.89 +Recreation,2012-11,111.35 +Communication,2012-10,112.93 +Furnishings,2012-07,112.88 +Motor fuels,2012-01,103.23 +Recreation,2013-01,113.80 +Clothing,2012-01,111.48 +Transport services,2013-02,97.89 +Communication,2012-02,112.25 +Transport services,2012-10,99.59 +Food,2012-03,108.30 +Clothing,2012-12,120.17 +Health,2012-03,109.72 +Furnishings,2013-02,118.06 +Clothing,2012-05,114.97 +Clothing,2012-04,115.59 +Clothing,2012-03,113.25 +Recreation,2012-04,109.05 +Recreation,2012-03,109.00 +Motor fuels,2012-12,112.38 +Transport services,2012-01,101.87 +Motor fuels,2013-01,107.03 +Health,2013-01,107.54 +Recreation,2012-07,109.85 +Health,2012-08,108.66 +Furnishings,2012-05,113.18 +Food,2012-01,109.42 +Food,2012-11,116.91 +Motor fuels,2012-08,115.10 +Furnishings,2012-01,110.96 +Recreation,2012-08,109.78 +Communication,2012-06,113.22 +Food,2012-04,109.47 +Communication,2012-05,112.98 +Communication,2012-08,112.69 +Transport services,2012-05,101.62 +Recreation,2012-01,107.71 +Communication,2012-04,112.68 +Motor fuels,2012-03,100.89 +Motor fuels,2012-11,115.68 +Food,2012-09,116.12 +Furnishings,2012-12,115.33 +Clothing,2012-06,116.27 +Food,2012-06,112.25 +Health,2012-06,107.65 +Furnishings,2012-10,114.22 +Clothing,2013-01,120.15 +Transport services,2012-08,100.69 +Motor fuels,2012-06,116.63 +Clothing,2012-09,118.84 +Clothing,2012-08,117.56 +Recreation,2012-10,111.31 +Transport services,2012-03,101.50 +Communication,2012-03,112.57 +Transport services,2013-03,98.55 +Transport services,2013-01,97.62 +Communication,2013-01,114.08 +Food,2012-05,108.50 +Health,2012-01,108.90 +Food,2012-12,120.19 +Furnishings,2013-01,116.37 +Furnishings,2012-09,113.57 +Furnishings,2012-04,113.86 +Transport services,2012-06,100.92 +Motor fuels,2013-02,107.26 +Health,2012-04,109.41 +Furnishings,2012-11,114.27 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf8d94f45fcfd76db2eedc229a38897ab63af26 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2013-02", + "comparison_month": "2012-02" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..8970c169b1ea9505e9eb215523a026d1414a14ac --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0042/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Transport services,2307.4 +Furnishings,1979.7 +Food,5880.6 +Recreation,3603.7 +Communication,981.3 +Health,1790.4 +Motor fuels,1426.8 +Clothing,1926.9 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0042/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-t0042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ede791b441fba5f96417a99ca7d5b3f308c0580f --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0042/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2013-02 (the current month) with 2012-02 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2012-02"` and `"2013-02"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2012-02 to 2013-02, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0042/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-t0042/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0042/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0042/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-t0042/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0042/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..df46157f08126265cda9684a19fb141ffa21bbd8 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/indices.csv @@ -0,0 +1,121 @@ +category,month,index +Health,2020-08,102.34 +Communication,2021-08,118.29 +Recreation,2020-08,99.69 +Restaurants,2021-01,106.70 +Restaurants,2021-09,107.66 +Food,2020-11,114.56 +Health,2021-03,105.09 +Motor fuels,2020-12,110.14 +Food,2020-10,114.03 +Communication,2021-04,117.30 +Health,2020-07,101.74 +Recreation,2020-10,99.48 +Restaurants,2021-02,106.10 +Recreation,2021-04,98.10 +Motor fuels,2021-06,114.34 +Motor fuels,2021-08,113.31 +Motor fuels,2021-03,110.56 +Communication,2021-01,116.10 +Transport services,2020-11,104.61 +Motor fuels,2021-09,117.79 +Housing,2020-07,106.13 +Restaurants,2020-08,103.02 +Communication,2020-10,114.46 +Food,2020-08,107.53 +Motor fuels,2021-07,115.53 +Health,2021-08,105.93 +Motor fuels,2020-08,104.84 +Food,2020-09,110.30 +Communication,2021-07,117.08 +Housing,2020-10,108.67 +Restaurants,2021-03,107.23 +Food,2020-07,105.54 +Housing,2021-05,109.80 +Recreation,2021-01,99.57 +Restaurants,2020-07,104.23 +Restaurants,2021-06,108.40 +Transport services,2020-07,104.76 +Recreation,2020-11,99.43 +Health,2021-06,106.14 +Food,2021-06,117.74 +Transport services,2021-06,105.37 +Health,2020-11,103.50 +Motor fuels,2020-11,110.31 +Restaurants,2021-07,108.30 +Communication,2020-11,114.84 +Housing,2021-03,109.24 +Food,2021-05,119.47 +Health,2021-04,105.50 +Recreation,2021-09,94.90 +Communication,2021-06,117.37 +Housing,2021-06,110.09 +Health,2021-05,105.76 +Recreation,2020-09,99.56 +Restaurants,2020-11,104.50 +Restaurants,2020-10,104.35 +Health,2020-12,104.18 +Transport services,2021-01,105.29 +Recreation,2020-12,99.16 +Restaurants,2021-08,108.72 +Recreation,2021-05,97.96 +Recreation,2021-06,96.89 +Food,2021-02,117.70 +Restaurants,2020-09,103.42 +Recreation,2021-07,96.37 +Health,2021-02,105.17 +Communication,2020-09,113.27 +Health,2020-09,103.43 +Food,2021-03,116.82 +Communication,2021-02,116.75 +Motor fuels,2020-07,110.10 +Motor fuels,2020-09,110.19 +Housing,2020-12,108.65 +Transport services,2021-07,105.97 +Health,2021-09,105.50 +Housing,2020-11,108.41 +Housing,2021-09,109.82 +Housing,2020-08,106.32 +Transport services,2020-08,104.90 +Transport services,2021-09,105.87 +Housing,2021-04,110.30 +Housing,2020-09,107.56 +Restaurants,2021-05,108.38 +Food,2021-08,118.44 +Recreation,2021-03,98.64 +Communication,2021-09,120.35 +Communication,2021-03,116.73 +Communication,2020-12,116.14 +Food,2020-12,111.81 +Health,2020-10,103.73 +Transport services,2021-03,104.94 +Housing,2021-01,108.92 +Communication,2020-07,111.60 +Food,2021-09,116.81 +Food,2021-07,118.27 +Food,2021-04,116.20 +Food,2021-01,115.65 +Motor fuels,2021-05,117.39 +Motor fuels,2021-02,109.22 +Housing,2021-08,110.51 +Health,2021-07,105.41 +Recreation,2021-02,99.50 +Recreation,2020-07,100.66 +Housing,2021-02,109.05 +Recreation,2021-08,95.52 +Health,2021-01,104.38 +Motor fuels,2021-01,107.16 +Transport services,2021-04,104.76 +Communication,2021-05,117.71 +Transport services,2021-08,106.14 +Restaurants,2020-12,106.27 +Transport services,2020-10,103.97 +Transport services,2021-05,104.90 +Motor fuels,2020-10,104.10 +Transport services,2021-02,105.10 +Communication,2020-08,112.00 +Transport services,2020-09,104.39 +Motor fuels,2021-04,115.16 +Housing,2021-07,110.65 +Transport services,2020-12,105.34 +Restaurants,2021-04,108.11 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..cf2c79ddc168a560ee1bdadc9e052ab02195490e --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2021-07", + "comparison_month": "2020-07" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..26e8128c07a8425daafdcd63bbe3c6cbc4012581 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0054/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Health,316.6 +Housing,1451.8 +Motor fuels,227.1 +Communication,142.4 +Transport services,441.8 +Recreation,730.3 +Restaurants,490.5 +Food,770.7 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0054/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-t0054/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29b831291646c23ed46bc16c158ff55d81e8fdfd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0054/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2021-07 (the current month) with 2020-07 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2020-07"` and `"2021-07"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2020-07 to 2021-07, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0054/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-t0054/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0054/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0054/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-t0054/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0054/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..6e9d76285c02c53fcf3d0bd0ea79dc986064a639 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/indices.csv @@ -0,0 +1,145 @@ +category,month,index +Health,2015-02,107.05 +Recreation,2015-09,97.93 +Food,2015-01,110.27 +Furnishings,2015-04,109.99 +Recreation,2015-10,98.66 +Recreation,2014-07,100.91 +Transport services,2015-09,113.26 +Restaurants,2015-04,106.27 +Restaurants,2014-11,105.29 +Health,2015-11,107.17 +Restaurants,2015-01,106.22 +Recreation,2015-05,98.28 +Recreation,2015-03,99.06 +Health,2014-09,105.09 +Transport services,2015-01,106.62 +Housing,2015-02,106.19 +Furnishings,2015-01,108.07 +Housing,2015-07,110.48 +Restaurants,2015-02,105.97 +Food,2014-08,105.59 +Housing,2015-11,110.67 +Furnishings,2015-02,108.97 +Alcohol and tobacco,2014-11,98.11 +Alcohol and tobacco,2015-07,95.49 +Food,2014-12,107.63 +Transport services,2014-07,100.83 +Furnishings,2014-09,103.26 +Housing,2015-10,110.50 +Alcohol and tobacco,2014-09,100.37 +Recreation,2015-06,97.51 +Transport services,2015-07,112.64 +Housing,2014-06,101.00 +Food,2015-11,120.26 +Alcohol and tobacco,2015-02,96.56 +Housing,2015-08,111.34 +Restaurants,2015-07,107.24 +Transport services,2015-10,114.80 +Health,2015-05,107.47 +Recreation,2015-07,97.67 +Restaurants,2015-09,106.72 +Recreation,2015-01,100.28 +Recreation,2014-08,100.80 +Transport services,2015-02,107.69 +Housing,2015-05,109.36 +Recreation,2014-10,101.26 +Alcohol and tobacco,2015-11,94.81 +Furnishings,2014-12,106.23 +Housing,2014-10,103.92 +Furnishings,2014-06,102.33 +Health,2014-11,105.31 +Health,2015-03,107.07 +Health,2014-10,105.90 +Alcohol and tobacco,2015-04,97.50 +Alcohol and tobacco,2015-10,95.35 +Health,2015-06,107.33 +Furnishings,2015-10,112.41 +Restaurants,2014-09,103.53 +Alcohol and tobacco,2015-01,96.74 +Recreation,2014-09,101.63 +Alcohol and tobacco,2015-08,95.06 +Furnishings,2015-07,111.28 +Health,2015-10,106.50 +Housing,2014-08,101.88 +Food,2015-06,115.71 +Health,2015-07,106.99 +Furnishings,2015-06,111.12 +Transport services,2015-11,115.74 +Transport services,2015-08,113.95 +Alcohol and tobacco,2014-12,97.35 +Restaurants,2015-08,106.45 +Food,2014-10,106.97 +Food,2014-06,104.30 +Transport services,2015-05,111.58 +Furnishings,2015-05,109.98 +Recreation,2014-11,100.42 +Food,2015-07,116.59 +Health,2015-04,107.61 +Food,2015-04,115.90 +Food,2015-10,118.15 +Alcohol and tobacco,2014-08,100.82 +Alcohol and tobacco,2015-06,96.65 +Housing,2015-04,107.22 +Restaurants,2014-06,102.20 +Housing,2014-11,105.64 +Restaurants,2014-10,104.31 +Transport services,2015-03,109.22 +Housing,2015-06,109.64 +Alcohol and tobacco,2015-03,96.76 +Restaurants,2014-12,105.52 +Restaurants,2014-08,103.22 +Recreation,2015-08,97.41 +Food,2015-02,111.14 +Recreation,2015-04,98.36 +Restaurants,2015-10,106.26 +Food,2014-07,104.72 +Restaurants,2015-06,107.00 +Restaurants,2014-07,102.68 +Furnishings,2015-09,111.56 +Alcohol and tobacco,2015-05,96.88 +Alcohol and tobacco,2014-06,101.56 +Health,2015-08,106.64 +Housing,2014-07,101.73 +Transport services,2015-06,111.25 +Restaurants,2015-05,106.70 +Health,2014-08,104.14 +Transport services,2014-10,102.70 +Transport services,2014-09,101.69 +Furnishings,2014-11,104.87 +Furnishings,2015-03,109.09 +Transport services,2014-08,101.24 +Transport services,2014-12,105.65 +Food,2014-09,104.51 +Food,2015-03,114.38 +Furnishings,2014-10,102.93 +Health,2014-06,104.38 +Restaurants,2015-03,106.53 +Recreation,2014-06,100.87 +Furnishings,2014-08,103.79 +Restaurants,2015-11,106.88 +Health,2015-01,107.40 +Furnishings,2014-07,103.00 +Recreation,2014-12,100.19 +Transport services,2015-04,110.50 +Transport services,2014-11,104.38 +Housing,2015-03,107.09 +Housing,2015-01,106.47 +Housing,2014-09,102.67 +Alcohol and tobacco,2014-10,99.75 +Alcohol and tobacco,2015-09,95.10 +Furnishings,2015-11,112.46 +Furnishings,2015-08,111.79 +Health,2015-09,107.19 +Food,2015-05,116.03 +Health,2014-07,103.95 +Housing,2014-12,105.71 +Housing,2015-09,111.43 +Recreation,2015-11,99.02 +Recreation,2015-02,99.40 +Alcohol and tobacco,2014-07,101.57 +Food,2014-11,105.89 +Food,2015-09,119.27 +Food,2015-08,116.92 +Health,2014-12,105.93 +Transport services,2014-06,100.57 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..080c794940315cb2cc6867eb1f7202e10dd45b9f --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2015-11", + "comparison_month": "2014-11" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..6e29a131156b881fef2692f654c0b4b138a349ee --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0066/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Food,3504.8 +Health,848.8 +Recreation,2142.3 +Housing,4506.5 +Furnishings,1341.6 +Restaurants,1539.5 +Transport services,2519.9 +Alcohol and tobacco,1144.3 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0066/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-t0066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9e5726207b73cc3b40ad498dc6c6928e383a35b1 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0066/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2015-11 (the current month) with 2014-11 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2014-11"` and `"2015-11"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2014-11 to 2015-11, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0066/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-t0066/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0066/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0066/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-t0066/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0066/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..d3c317accc3998e7714b2386fd9863a9459f8d21 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/indices.csv @@ -0,0 +1,153 @@ +category,month,index +Motor fuels,2017-02,104.61 +Motor fuels,2017-01,106.88 +Motor fuels,2017-12,102.26 +Health,2017-07,108.52 +Housing,2016-08,106.30 +Motor fuels,2016-10,108.49 +Communication,2017-08,108.59 +Housing,2016-11,107.81 +Communication,2017-06,106.99 +Health,2017-02,106.57 +Electricity and gas,2017-01,97.26 +Health,2017-01,106.18 +Housing,2017-05,109.43 +Motor fuels,2017-05,99.63 +Health,2017-12,111.77 +Transport services,2017-05,108.77 +Communication,2017-07,107.00 +Communication,2017-09,108.99 +Transport services,2017-04,108.40 +Electricity and gas,2016-11,94.21 +Communication,2017-04,105.99 +Housing,2017-12,115.31 +Health,2016-12,106.31 +Electricity and gas,2016-10,97.73 +Electricity and gas,2017-09,107.72 +Transport services,2016-11,109.68 +Food,2017-09,93.50 +Communication,2017-12,109.89 +Electricity and gas,2017-03,97.60 +Motor fuels,2016-12,106.90 +Health,2017-06,107.48 +Housing,2016-07,105.44 +Communication,2016-11,106.88 +Clothing,2017-08,111.02 +Communication,2017-03,105.34 +Motor fuels,2017-08,103.24 +Motor fuels,2018-01,100.48 +Health,2017-10,110.00 +Food,2016-07,101.08 +Housing,2016-12,107.99 +Food,2017-01,99.98 +Health,2017-11,110.50 +Health,2016-11,105.61 +Clothing,2017-11,108.19 +Health,2017-09,109.17 +Food,2017-08,95.40 +Food,2017-04,97.73 +Clothing,2016-10,113.01 +Health,2016-07,102.09 +Clothing,2016-07,111.81 +Motor fuels,2017-11,98.28 +Health,2016-10,104.63 +Electricity and gas,2017-10,107.77 +Communication,2017-10,110.33 +Clothing,2017-07,110.88 +Food,2016-09,98.42 +Transport services,2016-09,109.71 +Housing,2017-07,111.60 +Clothing,2016-09,112.47 +Motor fuels,2016-08,106.92 +Transport services,2016-12,108.99 +Clothing,2018-01,106.97 +Communication,2017-01,105.39 +Food,2017-05,96.22 +Motor fuels,2016-11,112.15 +Transport services,2017-12,110.14 +Food,2017-10,93.11 +Food,2016-10,97.62 +Transport services,2017-03,107.42 +Electricity and gas,2018-01,117.24 +Housing,2016-09,107.28 +Electricity and gas,2017-06,99.83 +Food,2017-03,98.48 +Transport services,2017-06,108.87 +Electricity and gas,2017-08,107.30 +Food,2016-11,97.71 +Motor fuels,2017-04,105.02 +Clothing,2017-05,112.84 +Clothing,2017-03,113.89 +Housing,2016-10,107.32 +Transport services,2016-07,110.50 +Clothing,2017-02,114.66 +Communication,2016-07,104.91 +Transport services,2017-07,107.93 +Electricity and gas,2016-09,97.90 +Transport services,2016-08,109.90 +Communication,2017-02,104.53 +Motor fuels,2017-10,100.99 +Food,2017-06,96.89 +Food,2017-12,96.10 +Clothing,2017-01,115.16 +Motor fuels,2016-09,107.87 +Electricity and gas,2016-08,100.95 +Health,2018-01,113.15 +Communication,2016-08,105.50 +Food,2016-12,99.00 +Communication,2016-10,106.11 +Housing,2017-04,110.08 +Health,2016-08,103.34 +Food,2016-08,100.18 +Health,2017-05,107.67 +Electricity and gas,2016-12,96.02 +Housing,2018-01,115.72 +Electricity and gas,2017-05,103.24 +Clothing,2017-10,108.65 +Food,2017-11,95.75 +Housing,2017-11,114.73 +Transport services,2017-08,107.74 +Clothing,2016-11,113.53 +Clothing,2016-08,111.88 +Motor fuels,2017-07,101.09 +Housing,2017-01,108.03 +Housing,2017-08,113.13 +Motor fuels,2017-03,104.94 +Food,2018-01,94.84 +Motor fuels,2017-06,96.70 +Electricity and gas,2017-04,97.59 +Housing,2017-10,113.77 +Communication,2017-05,106.57 +Clothing,2017-12,107.47 +Communication,2017-11,109.79 +Housing,2017-02,107.88 +Transport services,2017-10,109.68 +Motor fuels,2016-07,108.27 +Transport services,2017-09,108.05 +Food,2017-07,95.63 +Transport services,2017-11,110.18 +Health,2017-08,108.30 +Electricity and gas,2017-07,104.27 +Health,2016-09,104.18 +Clothing,2017-06,111.64 +Health,2017-03,106.95 +Transport services,2017-01,107.87 +Electricity and gas,2016-07,101.19 +Food,2017-02,99.40 +Housing,2017-03,109.51 +Communication,2016-12,106.90 +Transport services,2018-01,110.95 +Clothing,2016-12,114.50 +Housing,2017-06,111.01 +Clothing,2017-09,109.02 +Transport services,2016-10,109.32 +Electricity and gas,2017-12,116.95 +Housing,2017-09,113.61 +Clothing,2017-04,113.24 +Transport services,2017-02,107.33 +Motor fuels,2017-09,100.60 +Communication,2018-01,110.48 +Electricity and gas,2017-11,107.37 +Electricity and gas,2017-02,98.96 +Communication,2016-09,107.07 +Health,2017-04,106.75 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..bb19a714c4a9617196bedba109d51eb9c1a0b638 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/request.json @@ -0,0 +1,4 @@ +{ + "current_month": "2018-01", + "comparison_month": "2017-01" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..a526c34e168ccc2e32fc24f26013bd8ab86ea4eb --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0078/environment/workdir/weights.csv @@ -0,0 +1,9 @@ +category,weight +Clothing,1091.4 +Food,3576.0 +Health,933.7 +Housing,5559.9 +Motor fuels,943.9 +Communication,766.9 +Transport services,2891.6 +Electricity and gas,2048.5 diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0078/instruction.md b/tasks/price-index/price-index-inflation-contributions-d2-t0078/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a84eb85f9ba580f903ef982b58387ebe61e90f6 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0078/instruction.md @@ -0,0 +1,19 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in the period the weights refer to; the weights do not add up to 1 or to 1000, so divide by their sum. `indices.csv` gives each category's monthly price index, in no particular order and for more months than you need. Every category's index equals 100 in the period the weights refer to. + +Compare 2018-01 (the current month) with 2017-01 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2017-01"` and `"2018-01"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2017-01 to 2018-01, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0078/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d2-t0078/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0078/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d2-t0078/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d2-t0078/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d2-t0078/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..b94d6d0ebec815731778526dd98791ed167d1e51 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/indices.csv @@ -0,0 +1,199 @@ +category,month,index +Food,2021-01,100.31 +Housing,2021-12,207.11 +Restaurants,2021-10,99.63 +Health,2021-01,99.32 +Food,2021-08,101.51 +Food,2021-07,101.52 +Furnishings,2021-09,160.07 +Housing,2022-05,215.94 +Recreation,2021-04,99.53 +Clothing,2022-02,103.64 +Recreation,2021-08,102.19 +Clothing,2022-03,104.38 +Health,2021-08,102.30 +Health,2021-03,100.25 +Electricity and gas,2021-03,99.26 +Alcohol and tobacco,2021-02,100.00 +Clothing,2022-01,103.75 +Alcohol and tobacco,2021-04,101.97 +Electricity and gas,2021-09,106.18 +Housing,2021-04,187.78 +Housing,2022-02,212.10 +Recreation,2021-11,102.33 +Restaurants,2022-06,102.79 +Clothing,2021-10,103.58 +Housing,2021-08,196.72 +Motor fuels,2022-02,100.48 +Furnishings,2021-12,165.02 +Transport services,2021-04,196.26 +Restaurants,2021-12,100.48 +Furnishings,2021-08,157.55 +Restaurants,2021-05,99.32 +Electricity and gas,2021-10,106.65 +Food,2021-12,102.29 +Electricity and gas,2021-02,100.00 +Food,2021-02,100.00 +Recreation,2022-04,100.48 +Alcohol and tobacco,2021-07,104.46 +Transport services,2022-04,209.05 +Furnishings,2021-06,155.93 +Electricity and gas,2021-01,104.59 +Health,2022-01,103.52 +Furnishings,2022-02,167.92 +Alcohol and tobacco,2021-05,102.98 +Health,2022-05,104.79 +Electricity and gas,2022-02,101.06 +Transport services,2021-06,197.33 +Recreation,2021-01,99.81 +Housing,2021-05,189.91 +Restaurants,2021-04,99.33 +Alcohol and tobacco,2021-01,98.70 +Housing,2022-01,209.91 +Clothing,2022-04,104.80 +Restaurants,2022-01,100.60 +Recreation,2022-02,101.13 +Health,2021-12,103.15 +Food,2022-01,101.80 +Recreation,2021-02,100.00 +Recreation,2021-06,100.74 +Electricity and gas,2022-03,95.16 +Housing,2021-07,193.06 +Motor fuels,2021-09,97.04 +Transport services,2022-02,205.71 +Furnishings,2021-04,153.12 +Clothing,2021-03,100.52 +Health,2022-06,105.61 +Motor fuels,2021-04,99.76 +Furnishings,2022-03,169.80 +Furnishings,2022-01,165.86 +Alcohol and tobacco,2021-08,104.16 +Transport services,2021-07,200.72 +Alcohol and tobacco,2022-06,111.23 +Housing,2022-03,214.30 +Restaurants,2021-02,100.00 +Electricity and gas,2021-04,97.15 +Motor fuels,2022-06,106.72 +Health,2021-11,102.94 +Transport services,2021-01,195.66 +Housing,2021-01,185.20 +Food,2022-02,101.97 +Furnishings,2021-03,151.96 +Furnishings,2022-04,171.34 +Transport services,2022-06,214.05 +Housing,2021-03,186.73 +Electricity and gas,2021-12,103.49 +Clothing,2021-05,101.44 +Housing,2022-04,215.96 +Food,2021-06,100.23 +Motor fuels,2021-10,102.01 +Food,2022-05,103.90 +Motor fuels,2021-02,108.25 +Motor fuels,2021-06,99.09 +Recreation,2021-05,100.15 +Food,2022-03,104.21 +Electricity and gas,2021-06,93.23 +Transport services,2021-11,203.82 +Furnishings,2021-02,150.78 +Housing,2021-10,203.53 +Health,2021-04,100.28 +Transport services,2021-05,196.86 +Furnishings,2021-07,157.50 +Motor fuels,2022-01,102.17 +Alcohol and tobacco,2022-01,107.67 +Electricity and gas,2022-04,100.87 +Alcohol and tobacco,2021-10,104.31 +Motor fuels,2021-11,99.65 +Clothing,2022-06,105.56 +Restaurants,2022-05,101.62 +Restaurants,2021-03,99.15 +Furnishings,2022-06,172.23 +Recreation,2022-01,101.01 +Housing,2021-06,191.56 +Electricity and gas,2021-05,96.15 +Food,2021-05,99.05 +Furnishings,2021-11,164.21 +Food,2021-09,101.17 +Transport services,2021-08,201.28 +Recreation,2022-05,100.38 +Transport services,2022-03,204.64 +Motor fuels,2021-12,101.64 +Alcohol and tobacco,2022-03,109.41 +Motor fuels,2021-03,98.44 +Transport services,2021-09,201.96 +Motor fuels,2022-03,107.67 +Health,2021-02,100.00 +Food,2022-04,104.96 +Health,2022-04,104.42 +Clothing,2021-12,103.96 +Housing,2021-11,205.98 +Electricity and gas,2022-05,104.14 +Clothing,2021-11,104.47 +Food,2021-10,104.01 +Restaurants,2021-11,100.30 +Furnishings,2021-05,155.54 +Clothing,2021-07,102.14 +Motor fuels,2021-01,107.16 +Food,2021-11,103.52 +Health,2021-09,102.11 +Motor fuels,2021-05,96.61 +Clothing,2021-06,101.63 +Restaurants,2021-01,99.58 +Restaurants,2021-07,99.86 +Motor fuels,2021-08,99.34 +Transport services,2021-03,194.67 +Clothing,2021-01,98.80 +Clothing,2022-05,105.37 +Health,2021-06,101.16 +Motor fuels,2021-07,101.04 +Health,2022-02,104.82 +Furnishings,2021-01,150.29 +Clothing,2021-09,102.65 +Restaurants,2021-06,100.80 +Alcohol and tobacco,2021-03,100.96 +Furnishings,2022-05,172.03 +Clothing,2021-04,100.65 +Alcohol and tobacco,2021-12,105.81 +Recreation,2022-03,100.55 +Housing,2022-06,217.59 +Recreation,2021-12,102.32 +Recreation,2022-06,99.52 +Alcohol and tobacco,2022-05,110.25 +Electricity and gas,2022-01,103.46 +Recreation,2021-07,101.67 +Furnishings,2021-10,162.69 +Restaurants,2022-02,100.86 +Transport services,2021-02,197.96 +Restaurants,2022-04,101.32 +Clothing,2021-02,100.00 +Health,2022-03,104.83 +Transport services,2022-01,203.73 +Recreation,2021-09,102.38 +Transport services,2022-05,211.24 +Electricity and gas,2021-07,98.10 +Restaurants,2021-08,100.67 +Clothing,2021-08,102.49 +Transport services,2021-12,202.81 +Alcohol and tobacco,2021-09,103.81 +Housing,2021-02,184.88 +Food,2022-06,103.70 +Motor fuels,2022-05,112.20 +Electricity and gas,2021-11,105.37 +Recreation,2021-10,102.41 +Electricity and gas,2021-08,101.73 +Transport services,2021-10,202.20 +Food,2021-04,100.95 +Recreation,2021-03,100.19 +Health,2021-05,100.13 +Restaurants,2021-09,99.80 +Alcohol and tobacco,2022-02,108.66 +Food,2021-03,99.34 +Restaurants,2022-03,100.86 +Health,2021-07,101.17 +Electricity and gas,2022-06,105.38 +Alcohol and tobacco,2021-06,102.99 +Health,2021-10,102.60 +Motor fuels,2022-04,105.56 +Alcohol and tobacco,2022-04,109.97 +Housing,2021-09,200.29 +Alcohol and tobacco,2021-11,104.91 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..e56bed6c69874bcea364005a41a697b3bd076695 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2022-04", + "comparison_month": "2021-04", + "weight_reference_month": "2021-02" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..937f91b6db10d061c182f3ec1258736283a94911 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0010/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Food,3990.1,food +Clothing,1666.8,other +Restaurants,2793.4,other +Electricity and gas,1878.4,energy +Recreation,3701.2,other +Housing,8637.1,other +Transport services,2802.3,other +Furnishings,1993.6,other +Motor fuels,1590.1,energy +Health,1497.4,other +Alcohol and tobacco,1275.5,other diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0010/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-e0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1614742eb38d549a3106b2800c347d25443577e3 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0010/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2021-02, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2021-02: rebased index = 100 x published index / published index of the same category in 2021-02. Use the rebased indices everywhere below. + +Compare 2022-04 (the current month) with 2021-04 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2021-04"` and `"2022-04"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2021-04 to 2022-04, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0010/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-e0010/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0010/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0010/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-e0010/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0010/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..9e3339e1c36ada8b8432de549083ea4e0935b0b9 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/indices.csv @@ -0,0 +1,188 @@ +category,month,index +Transport services,2014-06,102.73 +Transport services,2014-03,100.26 +Communication,2015-05,100.66 +Health,2014-12,83.38 +Recreation,2014-10,105.52 +Furnishings,2014-06,178.53 +Motor fuels,2015-01,205.60 +Electricity and gas,2015-03,246.08 +Electricity and gas,2015-02,245.61 +Food,2014-12,195.94 +Electricity and gas,2014-06,226.26 +Recreation,2014-04,102.65 +Communication,2015-01,101.35 +Electricity and gas,2014-11,234.80 +Electricity and gas,2014-12,229.76 +Electricity and gas,2014-04,206.86 +Transport services,2014-08,104.90 +Electricity and gas,2014-08,232.18 +Alcohol and tobacco,2014-12,133.14 +Transport services,2014-04,100.64 +Alcohol and tobacco,2014-11,132.15 +Restaurants,2014-07,136.67 +Motor fuels,2014-11,189.02 +Clothing,2014-06,102.57 +Restaurants,2015-05,134.00 +Communication,2014-11,101.65 +Food,2014-07,204.72 +Motor fuels,2014-03,194.40 +Electricity and gas,2014-02,201.65 +Clothing,2014-12,108.27 +Motor fuels,2014-04,188.23 +Health,2015-05,85.14 +Health,2014-04,77.98 +Recreation,2015-04,109.99 +Furnishings,2014-04,179.76 +Clothing,2014-01,100.00 +Food,2015-02,193.72 +Health,2015-04,84.71 +Recreation,2015-02,108.57 +Health,2014-10,82.46 +Communication,2014-10,101.04 +Furnishings,2014-07,177.51 +Furnishings,2015-05,174.56 +Electricity and gas,2015-05,240.15 +Transport services,2014-11,106.09 +Furnishings,2014-10,176.77 +Restaurants,2015-04,135.73 +Furnishings,2015-02,176.85 +Electricity and gas,2014-09,220.23 +Recreation,2014-08,103.16 +Restaurants,2014-10,136.83 +Transport services,2015-01,108.31 +Food,2014-09,202.73 +Transport services,2015-03,108.90 +Recreation,2014-06,102.88 +Electricity and gas,2014-10,226.56 +Motor fuels,2014-12,192.44 +Clothing,2015-01,108.60 +Recreation,2014-02,100.46 +Communication,2015-03,101.49 +Recreation,2014-12,107.18 +Furnishings,2015-04,177.75 +Clothing,2014-02,99.99 +Food,2014-02,209.35 +Furnishings,2014-03,179.56 +Restaurants,2014-03,135.38 +Clothing,2014-04,100.33 +Furnishings,2015-03,176.75 +Transport services,2014-01,100.00 +Furnishings,2014-08,179.09 +Communication,2014-03,100.41 +Electricity and gas,2014-03,208.18 +Electricity and gas,2015-04,235.37 +Furnishings,2015-01,176.28 +Motor fuels,2014-05,176.77 +Motor fuels,2014-01,175.19 +Health,2014-02,77.10 +Recreation,2015-03,108.47 +Health,2014-06,79.30 +Communication,2014-09,100.60 +Alcohol and tobacco,2014-01,130.43 +Restaurants,2014-01,136.55 +Health,2014-09,81.44 +Restaurants,2015-02,135.49 +Food,2014-08,206.32 +Electricity and gas,2014-05,218.42 +Food,2014-03,207.97 +Health,2015-03,84.02 +Health,2014-03,77.03 +Clothing,2014-09,104.86 +Transport services,2014-05,101.88 +Alcohol and tobacco,2015-01,133.28 +Alcohol and tobacco,2014-05,129.01 +Food,2015-01,194.98 +Restaurants,2015-01,135.17 +Health,2014-11,83.39 +Motor fuels,2015-04,215.61 +Health,2014-07,79.71 +Motor fuels,2014-09,181.42 +Health,2014-05,78.86 +Communication,2014-04,99.89 +Furnishings,2014-12,177.56 +Transport services,2014-07,103.54 +Electricity and gas,2015-01,238.82 +Transport services,2014-12,107.14 +Transport services,2014-10,105.33 +Clothing,2015-03,109.76 +Alcohol and tobacco,2014-04,129.17 +Communication,2014-06,99.95 +Health,2014-08,80.14 +Alcohol and tobacco,2014-07,130.17 +Motor fuels,2015-05,197.12 +Alcohol and tobacco,2014-10,130.97 +Transport services,2014-02,99.77 +Recreation,2015-01,108.00 +Recreation,2014-07,102.90 +Food,2014-05,209.37 +Motor fuels,2014-07,172.72 +Food,2014-04,210.56 +Alcohol and tobacco,2015-03,132.95 +Transport services,2015-02,108.72 +Motor fuels,2015-03,213.40 +Health,2014-01,76.58 +Communication,2014-07,100.34 +Clothing,2015-02,108.82 +Restaurants,2014-02,136.29 +Restaurants,2014-11,136.37 +Recreation,2014-05,102.66 +Recreation,2015-05,110.67 +Alcohol and tobacco,2014-03,130.35 +Recreation,2014-09,104.45 +Food,2015-05,189.36 +Communication,2014-12,101.82 +Food,2014-01,213.16 +Furnishings,2014-11,177.38 +Food,2014-06,208.82 +Motor fuels,2014-02,186.79 +Clothing,2014-03,100.16 +Clothing,2014-05,101.61 +Restaurants,2014-12,135.54 +Transport services,2014-09,104.69 +Communication,2014-02,100.13 +Motor fuels,2014-06,176.18 +Restaurants,2014-09,137.31 +Food,2015-04,190.37 +Alcohol and tobacco,2014-09,131.44 +Motor fuels,2014-08,175.07 +Motor fuels,2015-02,221.85 +Electricity and gas,2014-01,203.84 +Alcohol and tobacco,2014-06,129.51 +Alcohol and tobacco,2015-05,134.72 +Food,2014-11,198.65 +Furnishings,2014-05,178.59 +Alcohol and tobacco,2014-08,130.33 +Transport services,2015-05,110.82 +Clothing,2015-05,112.50 +Transport services,2015-04,109.90 +Electricity and gas,2014-07,227.51 +Recreation,2014-11,106.51 +Clothing,2014-07,103.68 +Recreation,2014-03,101.16 +Clothing,2014-08,104.52 +Restaurants,2014-08,136.50 +Restaurants,2014-04,135.96 +Clothing,2015-04,110.98 +Communication,2015-04,100.41 +Food,2014-10,197.95 +Health,2015-02,84.63 +Health,2015-01,84.05 +Alcohol and tobacco,2015-04,133.43 +Restaurants,2014-06,135.71 +Furnishings,2014-09,177.03 +Restaurants,2014-05,136.54 +Communication,2014-05,100.08 +Alcohol and tobacco,2014-02,129.83 +Motor fuels,2014-10,181.48 +Communication,2014-08,99.86 +Restaurants,2015-03,135.74 +Alcohol and tobacco,2015-02,133.90 +Recreation,2014-01,100.00 +Clothing,2014-11,107.45 +Clothing,2014-10,105.84 +Communication,2015-02,101.72 +Furnishings,2014-01,178.20 +Communication,2014-01,100.00 +Furnishings,2014-02,178.19 +Food,2015-03,192.17 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..5fc59fe4e78ffae4c1f822c99b75f11c890907e7 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2015-03", + "comparison_month": "2014-03", + "weight_reference_month": "2014-01" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..d58c30bbbe87add8a9c2cc98f5203adfcd64c934 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0022/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Recreation,612.7,other +Transport services,615.5,other +Motor fuels,251.0,energy +Restaurants,426.0,other +Alcohol and tobacco,192.9,other +Communication,175.7,other +Electricity and gas,325.6,energy +Furnishings,349.6,other +Food,723.2,food +Clothing,258.4,other +Health,322.5,other diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0022/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-e0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c4ff5167870f7ec951658c5f286da26d30468ae2 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0022/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2014-01, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2014-01: rebased index = 100 x published index / published index of the same category in 2014-01. Use the rebased indices everywhere below. + +Compare 2015-03 (the current month) with 2014-03 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2014-03"` and `"2015-03"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2014-03 to 2015-03, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0022/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-e0022/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0022/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-e0022/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-e0022/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-e0022/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..f39ab98bba427be6edc0cb58612c7010206b82d5 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/indices.csv @@ -0,0 +1,177 @@ +category,month,index +Electricity and gas,2015-12,112.61 +Communication,2015-08,94.31 +Electricity and gas,2015-05,101.10 +Recreation,2015-12,191.79 +Transport services,2015-03,100.32 +Health,2016-02,104.65 +Transport services,2016-05,102.12 +Electricity and gas,2016-05,115.27 +Food,2015-08,219.56 +Housing,2015-08,103.53 +Communication,2015-04,97.13 +Health,2016-04,106.42 +Health,2016-03,105.24 +Clothing,2015-10,204.27 +Restaurants,2015-03,76.04 +Recreation,2016-02,194.89 +Electricity and gas,2015-03,98.03 +Alcohol and tobacco,2016-04,105.66 +Clothing,2016-04,206.86 +Electricity and gas,2016-04,111.04 +Alcohol and tobacco,2015-06,100.00 +Alcohol and tobacco,2015-11,104.12 +Transport services,2015-09,99.71 +Recreation,2015-09,187.23 +Restaurants,2015-12,76.84 +Health,2016-05,106.87 +Recreation,2016-04,195.60 +Food,2016-03,223.36 +Clothing,2016-02,206.58 +Food,2015-07,214.08 +Motor fuels,2016-02,177.11 +Transport services,2016-03,101.56 +Electricity and gas,2016-02,111.31 +Electricity and gas,2016-03,109.78 +Alcohol and tobacco,2016-02,106.13 +Food,2016-01,214.67 +Recreation,2016-01,193.49 +Housing,2016-01,109.04 +Recreation,2015-03,186.05 +Housing,2015-07,102.67 +Communication,2015-12,94.39 +Restaurants,2016-01,77.02 +Food,2016-04,230.65 +Recreation,2015-07,186.99 +Health,2015-05,100.66 +Alcohol and tobacco,2015-09,103.51 +Motor fuels,2015-12,164.04 +Motor fuels,2016-03,188.46 +Health,2015-06,101.53 +Restaurants,2016-05,76.10 +Motor fuels,2015-03,162.19 +Food,2015-04,199.41 +Housing,2015-05,101.72 +Restaurants,2016-03,75.98 +Transport services,2015-07,99.44 +Alcohol and tobacco,2015-05,99.90 +Motor fuels,2015-10,170.89 +Alcohol and tobacco,2016-03,105.50 +Clothing,2015-06,201.53 +Health,2015-12,103.83 +Clothing,2016-03,207.77 +Housing,2015-04,100.00 +Housing,2016-02,109.95 +Motor fuels,2016-04,195.65 +Electricity and gas,2015-02,100.73 +Housing,2015-10,105.84 +Alcohol and tobacco,2015-10,103.62 +Electricity and gas,2015-11,110.46 +Clothing,2015-08,202.39 +Food,2015-06,208.65 +Housing,2015-12,106.80 +Health,2015-03,99.68 +Food,2015-02,199.75 +Alcohol and tobacco,2016-05,106.20 +Communication,2016-02,94.69 +Clothing,2015-05,201.03 +Motor fuels,2015-06,162.99 +Electricity and gas,2015-10,111.84 +Communication,2015-11,93.99 +Communication,2016-04,93.35 +Health,2015-04,100.00 +Motor fuels,2015-11,161.84 +Food,2015-10,215.24 +Clothing,2015-02,193.56 +Recreation,2015-04,187.98 +Health,2016-01,104.67 +Clothing,2015-11,204.35 +Recreation,2016-03,195.22 +Alcohol and tobacco,2015-04,100.00 +Food,2016-02,218.22 +Food,2016-05,232.53 +Food,2015-05,203.68 +Communication,2016-03,93.54 +Alcohol and tobacco,2015-07,101.24 +Motor fuels,2015-05,166.25 +Communication,2015-06,96.75 +Communication,2015-03,97.34 +Communication,2015-09,94.71 +Transport services,2015-10,99.36 +Health,2015-08,102.85 +Restaurants,2015-09,76.61 +Alcohol and tobacco,2015-08,102.24 +Transport services,2016-02,100.24 +Health,2015-09,102.98 +Communication,2015-10,93.95 +Communication,2016-05,92.55 +Restaurants,2015-04,75.79 +Communication,2015-05,97.31 +Food,2015-12,213.99 +Electricity and gas,2015-07,100.81 +Transport services,2015-08,99.60 +Clothing,2015-07,201.05 +Communication,2015-07,95.35 +Housing,2016-04,111.48 +Communication,2016-01,94.25 +Restaurants,2015-07,75.99 +Recreation,2015-02,186.97 +Restaurants,2015-08,76.53 +Housing,2016-05,112.46 +Motor fuels,2015-09,169.31 +Transport services,2015-06,99.01 +Housing,2015-11,106.90 +Recreation,2015-08,186.47 +Recreation,2015-10,188.65 +Motor fuels,2015-02,151.05 +Transport services,2015-02,100.50 +Food,2015-11,215.02 +Motor fuels,2015-04,166.99 +Restaurants,2015-05,76.50 +Recreation,2016-05,195.97 +Restaurants,2016-04,76.29 +Housing,2015-06,102.18 +Restaurants,2016-02,76.30 +Transport services,2015-11,99.71 +Housing,2015-02,99.46 +Alcohol and tobacco,2016-01,105.59 +Housing,2015-03,98.53 +Clothing,2016-01,207.30 +Alcohol and tobacco,2015-02,100.59 +Clothing,2015-12,204.72 +Restaurants,2015-06,76.51 +Housing,2016-03,110.91 +Clothing,2015-09,202.28 +Electricity and gas,2015-08,107.72 +Motor fuels,2016-05,191.49 +Food,2015-09,215.14 +Electricity and gas,2016-01,107.40 +Transport services,2015-05,99.89 +Alcohol and tobacco,2015-12,104.65 +Motor fuels,2015-08,168.08 +Restaurants,2015-11,76.33 +Motor fuels,2015-07,173.32 +Recreation,2015-06,187.81 +Recreation,2015-05,187.48 +Clothing,2015-04,198.57 +Transport services,2015-12,100.09 +Health,2015-10,103.09 +Housing,2015-09,105.29 +Health,2015-07,101.88 +Restaurants,2015-10,75.86 +Electricity and gas,2015-09,109.41 +Motor fuels,2016-01,172.52 +Alcohol and tobacco,2015-03,100.83 +Clothing,2015-03,197.59 +Transport services,2015-04,100.00 +Restaurants,2015-02,75.90 +Health,2015-02,99.72 +Health,2015-11,103.89 +Recreation,2015-11,190.80 +Communication,2015-02,97.84 +Transport services,2016-04,101.39 +Clothing,2016-05,207.99 +Electricity and gas,2015-06,99.25 +Electricity and gas,2015-04,100.00 +Food,2015-03,199.54 +Transport services,2016-01,100.11 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..36527235dd872a3e418f4c34853f99ba35360590 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2016-05", + "comparison_month": "2015-05", + "weight_reference_month": "2015-04" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..81c7d97bdac5aef5a2c544f7bbb0fdd74525a92e --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0010/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Motor fuels,429.8,energy +Alcohol and tobacco,664.0,other +Electricity and gas,676.2,energy +Communication,353.1,other +Health,533.9,other +Housing,3298.6,other +Restaurants,915.2,other +Food,1724.6,food +Recreation,1240.5,other +Clothing,774.6,other +Transport services,1134.5,other diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0010/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-t0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8530f756be67d40aaa2cc1bd55b19cf3c380d6c8 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0010/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2015-04, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2015-04: rebased index = 100 x published index / published index of the same category in 2015-04. Use the rebased indices everywhere below. + +Compare 2016-05 (the current month) with 2015-05 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2015-05"` and `"2016-05"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2015-05 to 2016-05, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0010/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-t0010/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0010/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0010/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-t0010/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0010/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..40baedbf41723542bf3d0f999f0a0c85944910fe --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/indices.csv @@ -0,0 +1,166 @@ +category,month,index +Restaurants,2016-01,102.80 +Transport services,2016-01,105.63 +Clothing,2015-11,120.95 +Motor fuels,2016-03,134.22 +Motor fuels,2015-12,134.81 +Recreation,2016-02,97.66 +Recreation,2015-08,100.20 +Alcohol and tobacco,2015-03,100.00 +Health,2016-02,233.37 +Recreation,2015-06,99.92 +Alcohol and tobacco,2015-06,100.29 +Clothing,2016-01,122.88 +Motor fuels,2015-05,124.93 +Motor fuels,2015-11,138.05 +Housing,2015-06,147.78 +Alcohol and tobacco,2015-08,102.15 +Food,2015-03,100.00 +Alcohol and tobacco,2015-04,100.08 +Restaurants,2015-09,99.61 +Communication,2016-05,158.98 +Food,2016-01,102.19 +Clothing,2016-02,122.27 +Housing,2015-05,148.20 +Recreation,2015-09,99.73 +Alcohol and tobacco,2015-12,104.29 +Clothing,2015-06,118.12 +Housing,2015-04,147.27 +Recreation,2015-10,100.16 +Restaurants,2015-07,99.33 +Communication,2016-04,157.68 +Food,2015-05,101.66 +Food,2016-04,104.17 +Transport services,2016-02,107.74 +Alcohol and tobacco,2015-11,104.11 +Communication,2015-06,153.27 +Motor fuels,2015-06,129.41 +Alcohol and tobacco,2016-04,106.58 +Electricity and gas,2015-09,104.05 +Electricity and gas,2016-05,102.64 +Motor fuels,2015-04,128.19 +Motor fuels,2016-01,142.25 +Recreation,2015-11,100.17 +Clothing,2016-04,123.35 +Motor fuels,2015-09,139.78 +Health,2015-07,223.29 +Food,2016-03,105.17 +Housing,2015-11,149.97 +Communication,2015-05,153.27 +Electricity and gas,2016-03,106.66 +Health,2015-03,216.32 +Housing,2015-08,149.21 +Health,2015-05,218.34 +Motor fuels,2015-07,135.11 +Transport services,2015-10,105.21 +Transport services,2015-03,100.00 +Housing,2015-03,146.60 +Electricity and gas,2015-06,110.62 +Communication,2016-03,156.40 +Communication,2015-03,153.14 +Alcohol and tobacco,2015-05,99.45 +Restaurants,2016-02,103.70 +Electricity and gas,2015-08,108.36 +Recreation,2015-04,99.53 +Communication,2015-12,154.67 +Communication,2015-09,153.74 +Recreation,2016-05,96.75 +Recreation,2015-05,99.19 +Housing,2016-03,151.97 +Housing,2016-05,153.39 +Clothing,2016-05,124.14 +Housing,2015-07,149.71 +Restaurants,2015-04,99.86 +Communication,2015-10,153.68 +Motor fuels,2015-10,136.99 +Clothing,2015-04,116.70 +Food,2015-11,103.15 +Transport services,2015-09,104.85 +Restaurants,2015-08,98.68 +Electricity and gas,2016-04,104.37 +Health,2016-04,235.69 +Restaurants,2015-03,100.00 +Transport services,2015-07,102.65 +Electricity and gas,2015-10,108.34 +Clothing,2015-10,119.59 +Food,2015-08,101.34 +Food,2016-02,104.09 +Communication,2015-04,154.18 +Electricity and gas,2015-04,105.95 +Housing,2015-10,149.64 +Housing,2016-02,149.93 +Recreation,2015-07,100.19 +Transport services,2015-06,101.30 +Health,2015-10,226.76 +Health,2015-08,224.50 +Food,2015-06,102.36 +Restaurants,2016-03,104.02 +Electricity and gas,2015-05,108.96 +Restaurants,2015-05,99.40 +Restaurants,2015-11,101.57 +Transport services,2015-05,100.65 +Clothing,2015-12,121.69 +Food,2015-10,103.72 +Recreation,2015-03,100.00 +Communication,2015-08,154.28 +Transport services,2015-11,105.74 +Recreation,2016-04,96.46 +Health,2016-05,237.13 +Clothing,2015-07,118.22 +Clothing,2016-03,123.07 +Alcohol and tobacco,2015-10,103.15 +Communication,2015-11,154.52 +Restaurants,2015-06,99.04 +Restaurants,2015-12,101.75 +Recreation,2016-03,96.99 +Alcohol and tobacco,2015-07,100.81 +Transport services,2016-05,112.07 +Transport services,2015-04,100.04 +Housing,2016-01,149.95 +Clothing,2015-08,118.77 +Recreation,2016-01,98.94 +Food,2015-07,100.70 +Food,2016-05,104.86 +Transport services,2015-08,103.37 +Housing,2015-12,150.64 +Transport services,2015-12,106.06 +Communication,2016-02,157.32 +Health,2015-11,230.63 +Recreation,2015-12,99.66 +Electricity and gas,2016-01,113.97 +Restaurants,2016-05,104.34 +Food,2015-12,103.42 +Health,2015-06,221.67 +Restaurants,2015-10,100.91 +Food,2015-09,103.14 +Clothing,2015-09,119.00 +Restaurants,2016-04,104.30 +Alcohol and tobacco,2016-01,104.41 +Housing,2016-04,152.55 +Electricity and gas,2015-03,100.00 +Electricity and gas,2015-12,111.74 +Food,2015-04,100.46 +Transport services,2016-03,109.04 +Communication,2016-01,155.96 +Electricity and gas,2015-11,114.30 +Alcohol and tobacco,2016-03,106.65 +Health,2016-03,234.85 +Alcohol and tobacco,2015-09,102.20 +Communication,2015-07,153.54 +Alcohol and tobacco,2016-05,107.94 +Electricity and gas,2016-02,109.86 +Health,2016-01,231.07 +Motor fuels,2016-04,139.04 +Transport services,2016-04,110.75 +Motor fuels,2015-03,135.62 +Health,2015-12,231.67 +Health,2015-04,216.21 +Motor fuels,2015-08,141.81 +Motor fuels,2016-02,142.54 +Clothing,2015-05,117.42 +Motor fuels,2016-05,138.73 +Alcohol and tobacco,2016-02,105.52 +Clothing,2015-03,116.15 +Electricity and gas,2015-07,106.52 +Health,2015-09,224.55 +Housing,2015-09,149.03 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..1bedd58fada5b5f5a7fa91f0c3801dd7603c200b --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2016-05", + "comparison_month": "2015-05", + "weight_reference_month": "2015-03" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..421f33003b0cbda53bfbd3cd279c085b4d436103 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0022/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Motor fuels,109.3,energy +Electricity and gas,223.3,energy +Communication,74.8,other +Clothing,191.2,other +Restaurants,223.0,other +Housing,751.0,other +Food,414.6,food +Recreation,394.5,other +Health,104.3,other +Alcohol and tobacco,87.2,other +Transport services,178.4,other diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0022/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-t0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96af0da4b242841a95fe92bd5184c8a50895edba --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0022/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2015-03, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2015-03: rebased index = 100 x published index / published index of the same category in 2015-03. Use the rebased indices everywhere below. + +Compare 2016-05 (the current month) with 2015-05 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2015-05"` and `"2016-05"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2015-05 to 2016-05, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0022/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-t0022/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0022/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0022/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-t0022/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0022/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..730f3c285f751444c6d3cca84f07ff471812e7ff --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/indices.csv @@ -0,0 +1,199 @@ +category,month,index +Clothing,2016-12,211.20 +Furnishings,2017-05,132.27 +Recreation,2017-08,100.32 +Food,2017-05,94.25 +Furnishings,2017-03,129.97 +Health,2016-12,105.82 +Electricity and gas,2017-02,155.09 +Recreation,2017-01,100.06 +Transport services,2017-10,144.55 +Motor fuels,2016-11,97.03 +Transport services,2017-06,142.77 +Health,2017-07,104.15 +Food,2017-09,92.51 +Clothing,2016-09,211.74 +Transport services,2017-11,144.59 +Electricity and gas,2017-12,184.17 +Alcohol and tobacco,2017-10,112.11 +Health,2017-05,104.45 +Furnishings,2016-09,129.79 +Housing,2017-01,110.58 +Recreation,2017-10,99.95 +Alcohol and tobacco,2017-02,104.02 +Transport services,2017-01,139.00 +Recreation,2016-09,100.00 +Communication,2017-05,103.78 +Food,2017-11,93.84 +Communication,2017-09,103.03 +Electricity and gas,2016-08,148.30 +Transport services,2017-09,143.80 +Health,2017-10,103.54 +Housing,2017-11,110.62 +Food,2017-08,92.22 +Transport services,2016-08,134.52 +Clothing,2016-11,210.33 +Housing,2016-11,109.76 +Clothing,2017-08,211.97 +Motor fuels,2016-12,95.29 +Motor fuels,2017-03,93.68 +Recreation,2016-10,99.64 +Motor fuels,2017-04,90.13 +Electricity and gas,2017-03,151.14 +Food,2017-06,93.55 +Alcohol and tobacco,2016-12,101.15 +Communication,2017-04,104.34 +Food,2016-08,100.90 +Furnishings,2017-08,134.89 +Electricity and gas,2018-01,195.88 +Motor fuels,2017-02,99.71 +Furnishings,2016-12,131.99 +Recreation,2016-08,100.20 +Communication,2017-01,101.55 +Communication,2017-02,102.42 +Food,2018-01,94.81 +Clothing,2017-07,211.18 +Recreation,2018-01,101.02 +Health,2017-12,101.89 +Furnishings,2017-10,135.18 +Transport services,2016-09,136.00 +Recreation,2017-11,100.86 +Food,2016-09,100.00 +Clothing,2017-03,210.61 +Motor fuels,2017-06,95.50 +Alcohol and tobacco,2017-06,108.96 +Alcohol and tobacco,2017-04,107.77 +Alcohol and tobacco,2016-09,100.00 +Alcohol and tobacco,2017-08,110.46 +Alcohol and tobacco,2017-01,102.27 +Transport services,2017-03,142.59 +Health,2018-01,102.75 +Housing,2017-08,109.51 +Food,2017-02,97.21 +Furnishings,2017-02,130.74 +Communication,2016-09,100.00 +Housing,2017-03,110.63 +Health,2016-08,108.17 +Communication,2017-03,102.61 +Electricity and gas,2017-01,155.01 +Furnishings,2017-04,131.46 +Housing,2016-09,109.98 +Housing,2016-10,110.29 +Health,2017-08,103.01 +Clothing,2016-10,210.59 +Motor fuels,2017-10,97.64 +Furnishings,2017-01,131.32 +Electricity and gas,2017-06,162.98 +Housing,2016-08,109.87 +Housing,2017-09,110.69 +Recreation,2017-09,100.93 +Electricity and gas,2017-10,163.58 +Alcohol and tobacco,2017-12,113.96 +Alcohol and tobacco,2017-07,110.00 +Health,2017-11,102.68 +Clothing,2017-09,212.67 +Housing,2017-10,110.30 +Electricity and gas,2017-04,159.32 +Electricity and gas,2016-09,147.23 +Electricity and gas,2017-07,165.11 +Health,2017-01,106.09 +Housing,2017-02,110.27 +Furnishings,2016-11,130.84 +Recreation,2017-07,100.00 +Motor fuels,2016-09,100.00 +Food,2017-03,96.60 +Electricity and gas,2017-08,163.22 +Transport services,2017-05,141.36 +Motor fuels,2017-07,95.59 +Alcohol and tobacco,2018-01,114.79 +Food,2016-10,99.90 +Transport services,2017-02,141.56 +Motor fuels,2017-05,96.21 +Clothing,2017-04,210.31 +Motor fuels,2017-12,103.96 +Electricity and gas,2017-11,168.63 +Housing,2017-12,110.74 +Transport services,2016-10,135.75 +Health,2017-03,105.32 +Recreation,2017-12,101.11 +Health,2017-04,105.56 +Food,2017-04,96.15 +Food,2017-01,96.90 +Alcohol and tobacco,2016-08,99.26 +Communication,2016-08,98.49 +Health,2016-10,106.75 +Electricity and gas,2016-10,151.06 +Communication,2017-07,103.95 +Motor fuels,2017-11,104.25 +Communication,2016-12,100.40 +Recreation,2017-02,100.00 +Health,2017-09,103.74 +Clothing,2017-02,212.09 +Housing,2017-04,110.74 +Alcohol and tobacco,2016-11,100.90 +Motor fuels,2017-01,95.59 +Housing,2017-06,109.44 +Clothing,2017-11,215.83 +Furnishings,2017-09,135.15 +Food,2017-07,93.39 +Recreation,2017-06,100.22 +Food,2016-11,99.73 +Alcohol and tobacco,2017-11,112.72 +Food,2017-12,94.73 +Communication,2017-12,104.80 +Transport services,2017-08,145.09 +Health,2016-11,105.81 +Housing,2016-12,109.13 +Alcohol and tobacco,2016-10,100.37 +Electricity and gas,2017-09,168.20 +Furnishings,2017-07,134.31 +Electricity and gas,2016-12,155.41 +Motor fuels,2018-01,104.20 +Communication,2017-06,104.00 +Housing,2018-01,111.46 +Housing,2017-07,109.23 +Electricity and gas,2016-11,149.39 +Furnishings,2016-10,130.53 +Alcohol and tobacco,2017-05,107.90 +Recreation,2017-03,100.03 +Alcohol and tobacco,2017-09,111.50 +Motor fuels,2017-09,97.06 +Furnishings,2017-06,132.73 +Clothing,2017-10,213.14 +Health,2016-09,107.07 +Clothing,2017-05,209.47 +Housing,2017-05,110.29 +Furnishings,2016-08,129.76 +Food,2016-12,97.55 +Communication,2016-11,100.90 +Motor fuels,2016-10,99.15 +Clothing,2017-01,211.39 +Furnishings,2018-01,139.41 +Food,2017-10,93.99 +Transport services,2016-11,138.40 +Communication,2018-01,105.53 +Clothing,2016-08,211.79 +Motor fuels,2016-08,97.42 +Transport services,2017-12,144.96 +Transport services,2016-12,138.16 +Communication,2017-11,103.73 +Alcohol and tobacco,2017-03,106.23 +Furnishings,2017-12,137.84 +Communication,2016-10,100.23 +Recreation,2016-12,99.77 +Transport services,2018-01,145.49 +Electricity and gas,2017-05,156.84 +Recreation,2016-11,100.67 +Clothing,2018-01,213.49 +Furnishings,2017-11,136.34 +Clothing,2017-06,210.55 +Transport services,2017-07,144.69 +Motor fuels,2017-08,96.86 +Health,2017-02,105.64 +Recreation,2017-04,99.90 +Communication,2017-10,103.79 +Clothing,2017-12,213.65 +Transport services,2017-04,142.96 +Health,2017-06,103.63 +Communication,2017-08,103.81 +Recreation,2017-05,100.02 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..209f0fe21258ddf73387869c9b71e6bdd79852d2 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2017-12", + "comparison_month": "2016-12", + "weight_reference_month": "2016-09" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..c9064897f45afb78a92625067de2337942569629 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0034/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Recreation,2667.1,other +Food,5519.8,food +Clothing,1131.2,other +Housing,6582.2,other +Motor fuels,1615.0,energy +Transport services,2003.1,other +Furnishings,1757.0,other +Electricity and gas,1704.7,energy +Communication,1167.0,other +Alcohol and tobacco,954.7,other +Health,1404.8,other diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0034/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-t0034/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7cc017c8e26617391700b59d796d10f0fb4bc9ca --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0034/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2016-09, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2016-09: rebased index = 100 x published index / published index of the same category in 2016-09. Use the rebased indices everywhere below. + +Compare 2017-12 (the current month) with 2016-12 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2016-12"` and `"2017-12"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2016-12 to 2017-12, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0034/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-t0034/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0034/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0034/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-t0034/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0034/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..563173133ffdf1e3b00c3e6897a35eb734082404 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/indices.csv @@ -0,0 +1,188 @@ +category,month,index +Food,2014-11,161.28 +Food,2014-04,148.79 +Furnishings,2014-05,102.66 +Housing,2015-02,138.64 +Furnishings,2015-02,105.79 +Alcohol and tobacco,2015-01,103.77 +Food,2015-01,159.54 +Electricity and gas,2014-08,110.60 +Health,2014-02,164.75 +Restaurants,2014-01,128.87 +Food,2013-12,148.90 +Recreation,2014-01,99.75 +Health,2014-10,173.06 +Electricity and gas,2015-02,128.82 +Health,2014-06,166.68 +Clothing,2014-01,80.23 +Restaurants,2014-03,127.96 +Communication,2014-09,104.45 +Clothing,2014-09,84.75 +Food,2014-03,146.80 +Clothing,2014-12,84.08 +Housing,2014-10,134.79 +Housing,2013-12,126.70 +Communication,2014-01,100.60 +Electricity and gas,2013-12,110.79 +Food,2014-09,160.95 +Housing,2015-04,139.24 +Recreation,2014-08,100.63 +Electricity and gas,2014-09,112.45 +Motor fuels,2015-01,167.45 +Electricity and gas,2015-04,124.93 +Recreation,2014-10,100.70 +Clothing,2013-12,80.37 +Health,2015-03,173.65 +Food,2015-03,165.09 +Health,2014-03,165.26 +Alcohol and tobacco,2014-12,102.89 +Restaurants,2014-09,126.85 +Motor fuels,2015-04,170.60 +Health,2015-02,173.65 +Motor fuels,2014-09,182.65 +Restaurants,2015-04,124.46 +Motor fuels,2014-07,196.69 +Furnishings,2015-01,104.67 +Recreation,2014-02,100.00 +Motor fuels,2014-04,198.17 +Restaurants,2014-05,127.71 +Alcohol and tobacco,2014-06,102.11 +Communication,2013-12,100.00 +Housing,2014-08,132.60 +Recreation,2014-12,100.70 +Motor fuels,2015-02,173.47 +Alcohol and tobacco,2014-01,99.08 +Housing,2014-01,126.71 +Furnishings,2014-02,100.00 +Furnishings,2014-06,103.78 +Restaurants,2014-12,126.49 +Motor fuels,2014-03,183.45 +Clothing,2015-04,85.33 +Restaurants,2015-02,124.77 +Restaurants,2014-11,126.99 +Alcohol and tobacco,2014-04,101.61 +Communication,2014-12,107.20 +Communication,2014-10,105.09 +Communication,2014-08,104.45 +Motor fuels,2013-12,176.80 +Food,2014-07,151.26 +Clothing,2014-07,84.76 +Electricity and gas,2014-03,105.18 +Clothing,2015-03,85.08 +Recreation,2014-11,100.36 +Housing,2015-01,137.34 +Food,2014-02,147.06 +Housing,2014-07,130.82 +Restaurants,2015-03,124.83 +Food,2014-05,147.54 +Restaurants,2014-07,128.92 +Furnishings,2014-01,99.77 +Electricity and gas,2015-01,120.73 +Restaurants,2015-01,125.40 +Alcohol and tobacco,2014-08,102.47 +Alcohol and tobacco,2014-10,102.66 +Housing,2014-11,135.45 +Recreation,2014-09,99.60 +Communication,2014-07,102.81 +Recreation,2014-05,100.76 +Food,2015-02,162.24 +Food,2014-08,155.95 +Furnishings,2013-12,99.24 +Health,2014-07,168.20 +Furnishings,2015-03,105.44 +Housing,2014-06,129.26 +Electricity and gas,2014-02,108.31 +Housing,2014-12,135.71 +Communication,2014-03,100.74 +Clothing,2015-02,84.69 +Restaurants,2014-02,127.71 +Electricity and gas,2014-06,106.55 +Food,2015-04,165.14 +Communication,2014-11,106.32 +Furnishings,2014-08,103.89 +Alcohol and tobacco,2014-07,102.29 +Clothing,2014-10,84.63 +Recreation,2014-03,99.92 +Alcohol and tobacco,2014-11,102.77 +Alcohol and tobacco,2015-03,102.15 +Communication,2014-04,101.36 +Clothing,2014-08,84.83 +Recreation,2014-04,100.11 +Restaurants,2014-04,128.63 +Electricity and gas,2014-10,112.53 +Communication,2015-03,109.68 +Alcohol and tobacco,2014-03,100.51 +Restaurants,2014-06,128.53 +Furnishings,2014-10,104.98 +Recreation,2014-07,100.48 +Clothing,2014-03,81.95 +Furnishings,2014-09,103.15 +Housing,2014-09,133.42 +Clothing,2014-04,82.27 +Recreation,2015-02,100.84 +Motor fuels,2014-08,191.02 +Furnishings,2014-04,101.94 +Food,2014-12,159.13 +Housing,2014-03,127.41 +Health,2014-08,169.43 +Alcohol and tobacco,2014-02,100.00 +Motor fuels,2014-01,180.76 +Furnishings,2014-03,101.28 +Health,2014-12,173.44 +Furnishings,2014-11,105.26 +Motor fuels,2014-05,192.76 +Recreation,2014-06,101.06 +Alcohol and tobacco,2014-05,102.00 +Food,2014-06,150.38 +Restaurants,2013-12,128.89 +Housing,2014-04,128.26 +Health,2015-04,172.59 +Recreation,2013-12,100.24 +Motor fuels,2014-10,184.84 +Clothing,2015-01,84.02 +Electricity and gas,2014-01,108.32 +Electricity and gas,2015-03,128.66 +Food,2014-01,149.38 +Furnishings,2014-12,104.82 +Alcohol and tobacco,2015-04,102.55 +Recreation,2015-01,101.47 +Motor fuels,2014-11,175.51 +Communication,2015-04,110.27 +Alcohol and tobacco,2013-12,98.87 +Motor fuels,2014-02,186.02 +Communication,2015-02,108.53 +Motor fuels,2014-12,171.74 +Electricity and gas,2014-12,120.51 +Health,2014-04,165.26 +Electricity and gas,2014-11,116.18 +Health,2014-11,171.59 +Clothing,2014-02,81.46 +Clothing,2014-11,84.46 +Alcohol and tobacco,2015-02,102.62 +Communication,2014-02,100.43 +Communication,2015-01,107.52 +Furnishings,2015-04,106.08 +Housing,2014-02,127.07 +Restaurants,2014-10,126.31 +Restaurants,2014-08,126.99 +Motor fuels,2014-06,190.18 +Health,2014-01,162.12 +Electricity and gas,2014-04,104.76 +Furnishings,2014-07,103.78 +Motor fuels,2015-03,167.84 +Housing,2014-05,127.40 +Health,2013-12,162.59 +Electricity and gas,2014-05,108.80 +Health,2014-09,171.25 +Recreation,2015-03,100.96 +Recreation,2015-04,100.74 +Food,2014-10,163.15 +Health,2014-05,166.83 +Communication,2014-06,101.93 +Housing,2015-03,139.37 +Alcohol and tobacco,2014-09,101.90 +Clothing,2014-06,83.81 +Electricity and gas,2014-07,106.30 +Communication,2014-05,101.59 +Clothing,2014-05,82.53 +Health,2015-01,173.09 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..367cd8d0b5d7587e980f7bf7a519cc532afc8e18 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2015-04", + "comparison_month": "2014-04", + "weight_reference_month": "2014-02" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..fd436f94ad97a95c61ce6db7b5c6462680b24e44 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0046/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Alcohol and tobacco,1320.0,other +Recreation,4101.3,other +Electricity and gas,2424.5,energy +Communication,1146.6,other +Furnishings,2687.2,other +Motor fuels,1797.0,energy +Restaurants,2512.2,other +Housing,8068.0,other +Health,2262.0,other +Clothing,2305.1,other +Food,7635.1,food diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0046/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-t0046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cf4d01e233c08374fcaa1d1583c99bcac9907934 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0046/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2014-02, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2014-02: rebased index = 100 x published index / published index of the same category in 2014-02. Use the rebased indices everywhere below. + +Compare 2015-04 (the current month) with 2014-04 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2014-04"` and `"2015-04"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2014-04 to 2015-04, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0046/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-t0046/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0046/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0046/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-t0046/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0046/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..f1a6729e79824284585d24eb666f9b33620f2f10 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/indices.csv @@ -0,0 +1,177 @@ +category,month,index +Communication,2014-12,113.99 +Food,2014-09,97.27 +Restaurants,2015-03,187.04 +Transport services,2014-10,104.84 +Clothing,2015-04,74.65 +Communication,2015-06,118.03 +Recreation,2014-08,102.45 +Restaurants,2015-06,184.17 +Health,2015-05,172.71 +Alcohol and tobacco,2015-02,164.38 +Health,2015-06,174.91 +Health,2014-07,159.53 +Recreation,2015-03,109.58 +Communication,2015-02,115.70 +Transport services,2014-11,105.69 +Communication,2014-06,111.66 +Recreation,2014-11,105.79 +Restaurants,2014-07,184.36 +Health,2014-06,159.00 +Food,2015-05,97.83 +Recreation,2015-05,111.66 +Recreation,2014-07,102.02 +Food,2014-04,100.77 +Alcohol and tobacco,2014-05,158.39 +Alcohol and tobacco,2014-06,158.67 +Alcohol and tobacco,2014-10,161.05 +Recreation,2014-05,100.00 +Clothing,2014-05,68.37 +Transport services,2014-09,104.24 +Recreation,2014-09,104.14 +Transport services,2014-03,98.52 +Electricity and gas,2015-05,124.70 +Transport services,2015-01,107.09 +Restaurants,2014-10,182.76 +Housing,2014-06,199.46 +Restaurants,2014-09,184.72 +Alcohol and tobacco,2014-03,157.55 +Health,2014-05,157.31 +Food,2014-12,98.52 +Motor fuels,2014-06,143.94 +Electricity and gas,2014-05,100.00 +Clothing,2014-08,69.15 +Food,2014-10,96.53 +Food,2014-07,98.46 +Electricity and gas,2014-12,111.28 +Recreation,2015-01,108.82 +Housing,2014-04,201.36 +Electricity and gas,2015-03,118.70 +Communication,2015-03,115.63 +Housing,2015-02,196.77 +Restaurants,2014-08,184.17 +Housing,2015-04,196.62 +Motor fuels,2014-04,139.95 +Clothing,2014-04,68.72 +Communication,2014-07,113.06 +Housing,2014-05,199.61 +Food,2014-05,100.00 +Transport services,2015-06,111.70 +Communication,2014-08,113.38 +Electricity and gas,2015-02,117.00 +Health,2014-04,155.44 +Housing,2015-06,196.88 +Transport services,2015-04,110.36 +Housing,2015-03,196.72 +Electricity and gas,2015-06,131.05 +Housing,2014-12,196.40 +Recreation,2014-12,107.03 +Clothing,2015-02,73.95 +Alcohol and tobacco,2015-06,162.78 +Alcohol and tobacco,2015-04,164.26 +Housing,2014-07,200.12 +Motor fuels,2015-02,140.72 +Health,2015-02,170.68 +Restaurants,2014-06,182.85 +Recreation,2015-06,112.50 +Housing,2014-11,198.12 +Recreation,2014-06,100.16 +Food,2014-11,97.78 +Communication,2015-05,116.28 +Alcohol and tobacco,2014-11,161.99 +Alcohol and tobacco,2015-03,164.31 +Clothing,2014-11,70.88 +Health,2014-09,163.00 +Electricity and gas,2014-04,105.04 +Food,2015-06,100.15 +Housing,2014-10,197.44 +Motor fuels,2014-05,150.12 +Alcohol and tobacco,2014-12,163.98 +Alcohol and tobacco,2014-04,159.25 +Housing,2015-01,196.21 +Food,2015-02,100.15 +Clothing,2015-01,72.99 +Health,2015-04,170.97 +Restaurants,2014-11,183.65 +Health,2014-12,168.06 +Clothing,2014-07,68.57 +Electricity and gas,2014-08,108.52 +Clothing,2014-10,71.02 +Recreation,2014-03,98.13 +Clothing,2014-03,67.86 +Motor fuels,2014-08,151.61 +Transport services,2014-05,100.00 +Food,2014-08,97.82 +Communication,2014-10,113.02 +Motor fuels,2015-05,140.42 +Health,2014-10,164.90 +Communication,2014-09,112.51 +Motor fuels,2014-11,141.59 +Health,2015-01,170.22 +Food,2014-03,101.70 +Transport services,2014-06,100.53 +Clothing,2014-09,69.89 +Housing,2014-09,196.62 +Recreation,2015-04,110.53 +Food,2015-03,99.40 +Motor fuels,2015-03,143.99 +Communication,2014-05,110.98 +Communication,2014-04,110.50 +Electricity and gas,2015-01,114.73 +Restaurants,2014-03,182.37 +Recreation,2014-04,98.73 +Transport services,2015-03,109.31 +Electricity and gas,2014-11,114.59 +Alcohol and tobacco,2014-09,159.09 +Transport services,2014-08,102.21 +Clothing,2014-12,72.23 +Motor fuels,2014-03,144.57 +Alcohol and tobacco,2014-08,159.00 +Alcohol and tobacco,2015-01,163.65 +Clothing,2015-06,75.11 +Transport services,2015-02,107.85 +Transport services,2014-04,99.03 +Health,2015-03,171.34 +Restaurants,2015-02,185.61 +Clothing,2014-06,68.00 +Motor fuels,2015-01,139.99 +Transport services,2015-05,111.52 +Food,2015-04,96.79 +Food,2014-06,98.69 +Alcohol and tobacco,2015-05,163.28 +Health,2014-11,167.95 +Transport services,2014-07,101.53 +Motor fuels,2014-09,142.65 +Restaurants,2014-12,184.22 +Housing,2014-08,197.29 +Restaurants,2015-04,186.43 +Motor fuels,2014-10,140.30 +Housing,2014-03,200.03 +Motor fuels,2014-12,138.07 +Clothing,2015-03,74.06 +Communication,2014-11,114.47 +Motor fuels,2015-06,133.14 +Alcohol and tobacco,2014-07,158.31 +Clothing,2015-05,75.09 +Transport services,2014-12,106.69 +Electricity and gas,2014-07,111.15 +Food,2015-01,100.84 +Restaurants,2014-04,184.27 +Restaurants,2014-05,183.89 +Health,2014-03,156.40 +Health,2014-08,160.85 +Electricity and gas,2015-04,120.17 +Recreation,2014-10,104.85 +Restaurants,2015-01,185.65 +Communication,2015-01,114.59 +Communication,2015-04,115.94 +Electricity and gas,2014-10,113.80 +Motor fuels,2014-07,152.94 +Electricity and gas,2014-03,101.18 +Electricity and gas,2014-06,108.50 +Housing,2015-05,196.62 +Restaurants,2015-05,186.30 +Communication,2014-03,110.48 +Electricity and gas,2014-09,111.24 +Recreation,2015-02,109.42 +Motor fuels,2015-04,141.08 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..ec509c44d12ba9716952833ac04ad3a14f6d2a04 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2015-06", + "comparison_month": "2014-06", + "weight_reference_month": "2014-05" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..138ca3ae78ed5c76cdd736ce0765ac55276f87eb --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0058/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Communication,754.0,other +Transport services,1873.8,other +Restaurants,2001.1,other +Recreation,2103.3,other +Alcohol and tobacco,719.0,other +Electricity and gas,979.1,energy +Motor fuels,1107.8,energy +Housing,3481.9,other +Clothing,817.2,other +Food,3217.3,food +Health,1047.5,other diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0058/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-t0058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c16f73d997c970545a84c3796c6926651713c03 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0058/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2014-05, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2014-05: rebased index = 100 x published index / published index of the same category in 2014-05. Use the rebased indices everywhere below. + +Compare 2015-06 (the current month) with 2014-06 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2014-06"` and `"2015-06"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2014-06 to 2015-06, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0058/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-t0058/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0058/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0058/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-t0058/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0058/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..69c6fde3414ccbfd49fe1e58db1143700a699eff --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/indices.csv @@ -0,0 +1,199 @@ +category,month,index +Food,2022-03,100.20 +Alcohol and tobacco,2023-05,142.95 +Clothing,2023-02,168.14 +Housing,2023-02,99.37 +Alcohol and tobacco,2022-04,146.10 +Furnishings,2022-05,100.24 +Food,2022-07,100.38 +Restaurants,2022-05,203.37 +Recreation,2022-10,159.08 +Food,2022-05,101.03 +Transport services,2022-02,176.07 +Clothing,2022-02,155.92 +Motor fuels,2023-04,88.62 +Health,2022-11,98.50 +Food,2021-12,102.39 +Alcohol and tobacco,2022-07,147.58 +Health,2023-01,97.21 +Clothing,2022-03,157.68 +Housing,2022-06,100.12 +Housing,2023-05,99.17 +Health,2022-12,97.89 +Recreation,2022-04,158.84 +Transport services,2022-05,174.08 +Motor fuels,2023-02,94.77 +Alcohol and tobacco,2021-12,147.54 +Housing,2023-03,99.53 +Furnishings,2022-01,99.50 +Clothing,2022-12,166.05 +Health,2022-03,99.26 +Motor fuels,2022-09,97.80 +Furnishings,2023-01,105.91 +Alcohol and tobacco,2022-05,147.58 +Furnishings,2022-03,99.64 +Motor fuels,2022-02,100.00 +Motor fuels,2022-06,99.34 +Housing,2023-01,99.07 +Transport services,2022-01,176.88 +Recreation,2021-12,158.87 +Recreation,2022-03,160.37 +Recreation,2023-03,159.98 +Clothing,2021-12,156.45 +Restaurants,2022-01,200.00 +Clothing,2022-09,162.51 +Clothing,2022-10,163.02 +Furnishings,2023-03,106.69 +Housing,2022-02,100.00 +Health,2023-03,98.43 +Furnishings,2022-09,103.74 +Housing,2023-04,99.50 +Food,2022-02,100.25 +Housing,2022-04,100.66 +Transport services,2022-08,171.04 +Motor fuels,2022-11,95.71 +Motor fuels,2022-03,94.30 +Housing,2022-03,100.44 +Furnishings,2021-12,97.97 +Clothing,2023-01,166.43 +Food,2023-03,101.39 +Restaurants,2022-06,202.80 +Recreation,2022-09,159.56 +Motor fuels,2022-12,100.27 +Transport services,2022-11,170.22 +Furnishings,2023-04,106.52 +Recreation,2022-08,158.55 +Recreation,2022-02,159.90 +Health,2022-05,97.34 +Electricity and gas,2022-06,170.86 +Electricity and gas,2022-05,173.38 +Transport services,2023-02,171.12 +Health,2022-09,99.23 +Transport services,2022-12,171.38 +Furnishings,2022-06,101.72 +Housing,2022-01,100.03 +Restaurants,2023-02,204.73 +Motor fuels,2022-08,99.16 +Clothing,2023-04,169.31 +Furnishings,2022-11,106.10 +Furnishings,2023-02,105.99 +Alcohol and tobacco,2022-03,146.86 +Transport services,2023-05,172.78 +Restaurants,2022-04,201.28 +Food,2022-04,101.03 +Recreation,2023-05,158.05 +Housing,2021-12,101.16 +Electricity and gas,2023-03,181.31 +Motor fuels,2022-07,95.57 +Motor fuels,2023-05,89.03 +Health,2023-05,98.78 +Restaurants,2022-03,202.61 +Alcohol and tobacco,2022-01,148.38 +Health,2023-02,97.90 +Restaurants,2023-01,205.12 +Furnishings,2022-04,100.82 +Restaurants,2022-11,204.96 +Alcohol and tobacco,2023-01,145.21 +Transport services,2022-04,174.57 +Alcohol and tobacco,2023-04,143.78 +Motor fuels,2022-10,91.20 +Transport services,2022-07,173.06 +Furnishings,2022-12,106.37 +Furnishings,2022-08,103.08 +Motor fuels,2022-05,95.10 +Transport services,2023-03,171.26 +Housing,2022-11,99.46 +Housing,2022-05,100.69 +Restaurants,2022-02,200.55 +Housing,2022-08,99.20 +Alcohol and tobacco,2023-03,143.51 +Restaurants,2021-12,198.92 +Health,2022-01,100.07 +Food,2023-05,102.19 +Motor fuels,2022-04,91.19 +Transport services,2021-12,177.52 +Recreation,2022-07,158.21 +Health,2021-12,100.64 +Housing,2022-07,99.74 +Health,2022-07,98.32 +Electricity and gas,2022-08,175.90 +Alcohol and tobacco,2023-02,144.01 +Restaurants,2022-09,202.70 +Transport services,2023-01,170.46 +Restaurants,2023-04,203.29 +Alcohol and tobacco,2022-09,146.22 +Alcohol and tobacco,2022-06,147.27 +Electricity and gas,2022-04,192.90 +Electricity and gas,2022-07,167.69 +Transport services,2022-06,173.26 +Health,2022-08,98.51 +Clothing,2022-04,160.20 +Restaurants,2023-05,204.09 +Recreation,2022-01,158.33 +Electricity and gas,2023-05,216.27 +Furnishings,2022-07,102.70 +Recreation,2023-02,158.25 +Electricity and gas,2022-12,184.55 +Restaurants,2022-12,205.28 +Alcohol and tobacco,2022-02,147.60 +Motor fuels,2023-03,91.74 +Electricity and gas,2023-04,193.58 +Housing,2022-12,99.76 +Clothing,2023-05,169.70 +Housing,2022-10,99.82 +Food,2022-01,101.38 +Furnishings,2022-10,104.63 +Food,2022-06,99.90 +Health,2022-02,100.00 +Electricity and gas,2022-02,191.18 +Alcohol and tobacco,2022-08,147.67 +Food,2022-12,101.06 +Housing,2022-09,98.95 +Motor fuels,2021-12,103.32 +Electricity and gas,2022-11,192.54 +Recreation,2023-01,158.09 +Food,2022-11,99.57 +Restaurants,2022-08,202.30 +Electricity and gas,2023-02,186.28 +Electricity and gas,2022-01,195.14 +Transport services,2023-04,172.07 +Food,2023-01,99.83 +Recreation,2023-04,158.01 +Health,2022-10,98.18 +Clothing,2022-05,160.50 +Food,2022-10,100.95 +Food,2023-02,100.92 +Alcohol and tobacco,2022-10,144.98 +Clothing,2023-03,170.49 +Health,2022-06,97.84 +Electricity and gas,2022-09,181.02 +Electricity and gas,2022-03,186.68 +Food,2023-04,101.65 +Electricity and gas,2021-12,184.99 +Alcohol and tobacco,2022-11,146.26 +Electricity and gas,2022-10,187.87 +Food,2022-08,99.82 +Motor fuels,2022-01,104.67 +Recreation,2022-11,157.00 +Food,2022-09,100.86 +Transport services,2022-03,176.10 +Clothing,2022-01,157.79 +Furnishings,2023-05,108.09 +Alcohol and tobacco,2022-12,146.00 +Restaurants,2022-07,202.41 +Restaurants,2022-10,204.77 +Electricity and gas,2023-01,186.20 +Recreation,2022-05,158.17 +Recreation,2022-12,157.83 +Transport services,2022-10,169.88 +Clothing,2022-07,162.32 +Health,2022-04,97.78 +Clothing,2022-08,162.23 +Transport services,2022-09,169.73 +Clothing,2022-11,164.80 +Furnishings,2022-02,100.00 +Clothing,2022-06,161.18 +Health,2023-04,98.56 +Recreation,2022-06,158.73 +Motor fuels,2023-01,96.16 +Restaurants,2023-03,204.22 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..6ccbd1bbbe312ef4bafba9ca4736ad8a8812c742 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2023-04", + "comparison_month": "2022-04", + "weight_reference_month": "2022-02" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..b5edaecfc2e6e65c8315beaac96ae50e9b42bd43 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0070/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Recreation,1516.2,other +Restaurants,1311.7,other +Clothing,657.8,other +Food,3167.4,food +Housing,2455.6,other +Electricity and gas,947.7,energy +Motor fuels,889.4,energy +Transport services,1015.1,other +Health,943.8,other +Alcohol and tobacco,489.0,other +Furnishings,1135.9,other diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0070/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-t0070/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..559e271cf06861c4ea9a1c85c7e2006f6ce9f2dc --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0070/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2022-02, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2022-02: rebased index = 100 x published index / published index of the same category in 2022-02. Use the rebased indices everywhere below. + +Compare 2023-04 (the current month) with 2022-04 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2022-04"` and `"2023-04"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2022-04 to 2023-04, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0070/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-t0070/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0070/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0070/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-t0070/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0070/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/Dockerfile b/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/indices.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/indices.csv new file mode 100644 index 0000000000000000000000000000000000000000..60addec9fa441e9cfcbd9e26123774be8af4ac60 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/indices.csv @@ -0,0 +1,210 @@ +category,month,index +Electricity and gas,2020-01,98.21 +Alcohol and tobacco,2020-02,63.29 +Restaurants,2020-04,105.94 +Health,2019-09,100.90 +Alcohol and tobacco,2019-07,61.40 +Clothing,2019-04,61.44 +Food,2019-05,126.64 +Communication,2020-01,100.78 +Transport services,2020-02,113.86 +Furnishings,2020-09,95.60 +Electricity and gas,2019-11,100.49 +Restaurants,2020-03,104.89 +Recreation,2020-06,102.16 +Food,2019-11,129.18 +Restaurants,2019-11,103.52 +Motor fuels,2020-04,147.61 +Clothing,2019-07,61.31 +Recreation,2020-07,102.42 +Transport services,2019-04,107.70 +Alcohol and tobacco,2019-10,62.22 +Recreation,2020-03,102.76 +Alcohol and tobacco,2020-06,64.53 +Restaurants,2020-06,106.84 +Transport services,2019-05,108.79 +Furnishings,2020-05,96.68 +Health,2019-05,99.06 +Electricity and gas,2020-07,98.47 +Restaurants,2020-07,107.57 +Restaurants,2019-07,101.41 +Transport services,2020-06,119.24 +Alcohol and tobacco,2019-03,60.23 +Alcohol and tobacco,2019-09,61.79 +Restaurants,2020-09,109.19 +Communication,2019-03,99.66 +Communication,2020-05,101.13 +Motor fuels,2020-02,135.76 +Motor fuels,2019-03,99.57 +Electricity and gas,2020-06,95.95 +Furnishings,2019-03,98.93 +Clothing,2019-05,61.89 +Motor fuels,2019-07,105.97 +Communication,2019-06,100.00 +Recreation,2020-04,102.73 +Clothing,2020-09,64.52 +Transport services,2020-07,119.93 +Recreation,2020-05,102.58 +Electricity and gas,2019-05,96.07 +Motor fuels,2019-06,100.00 +Health,2019-07,99.65 +Alcohol and tobacco,2019-12,62.47 +Communication,2019-05,99.59 +Electricity and gas,2019-04,91.60 +Food,2019-07,125.13 +Transport services,2019-10,111.78 +Health,2019-03,99.16 +Health,2020-08,104.12 +Furnishings,2020-06,97.01 +Furnishings,2020-03,98.55 +Recreation,2019-06,100.00 +Health,2019-12,101.71 +Clothing,2020-08,64.21 +Restaurants,2019-09,102.35 +Health,2020-07,103.47 +Health,2019-06,100.00 +Clothing,2020-06,63.26 +Motor fuels,2020-05,141.39 +Electricity and gas,2019-03,89.99 +Food,2020-08,123.92 +Motor fuels,2019-04,105.40 +Alcohol and tobacco,2019-05,61.39 +Communication,2020-08,100.48 +Restaurants,2019-05,98.98 +Furnishings,2020-02,99.18 +Electricity and gas,2020-05,99.11 +Alcohol and tobacco,2020-09,65.26 +Food,2019-06,126.39 +Furnishings,2019-05,99.05 +Health,2020-03,103.15 +Food,2019-12,129.64 +Restaurants,2019-10,103.63 +Communication,2020-03,101.43 +Motor fuels,2020-08,154.40 +Food,2019-08,126.94 +Restaurants,2020-02,104.31 +Alcohol and tobacco,2020-05,63.82 +Recreation,2020-02,102.65 +Communication,2020-02,102.04 +Clothing,2019-09,61.26 +Clothing,2020-04,62.86 +Alcohol and tobacco,2019-06,61.36 +Food,2020-03,126.29 +Transport services,2019-06,109.59 +Communication,2019-11,101.31 +Motor fuels,2019-05,102.12 +Health,2020-05,102.89 +Communication,2019-12,100.02 +Food,2020-05,122.84 +Communication,2020-06,100.50 +Health,2020-01,101.90 +Health,2019-10,101.74 +Electricity and gas,2020-09,96.57 +Food,2020-01,128.11 +Communication,2020-07,99.98 +Clothing,2019-11,60.98 +Restaurants,2019-08,101.16 +Clothing,2020-07,63.65 +Communication,2019-04,99.46 +Recreation,2019-05,99.97 +Food,2019-04,125.46 +Furnishings,2020-04,97.91 +Health,2019-04,99.67 +Health,2019-08,100.36 +Electricity and gas,2019-09,104.98 +Recreation,2020-08,102.82 +Restaurants,2020-08,109.06 +Furnishings,2019-04,99.07 +Food,2019-03,124.93 +Clothing,2020-01,61.62 +Recreation,2019-09,101.63 +Communication,2019-07,99.93 +Transport services,2019-09,111.59 +Electricity and gas,2019-06,100.00 +Restaurants,2020-01,104.93 +Health,2020-04,102.98 +Electricity and gas,2020-03,94.86 +Recreation,2020-01,102.02 +Motor fuels,2019-10,103.53 +Clothing,2020-02,62.25 +Electricity and gas,2020-02,95.36 +Clothing,2019-08,61.12 +Furnishings,2019-08,100.00 +Alcohol and tobacco,2019-08,61.55 +Transport services,2020-03,114.83 +Clothing,2019-10,60.87 +Motor fuels,2020-07,150.00 +Food,2020-06,122.36 +Electricity and gas,2019-12,100.71 +Recreation,2019-07,101.02 +Transport services,2020-05,117.71 +Food,2019-10,128.61 +Alcohol and tobacco,2019-11,62.35 +Alcohol and tobacco,2019-04,60.89 +Recreation,2019-10,101.50 +Recreation,2019-04,98.96 +Furnishings,2019-10,100.41 +Restaurants,2020-05,106.27 +Alcohol and tobacco,2020-07,65.07 +Furnishings,2019-07,99.17 +Transport services,2020-01,113.18 +Restaurants,2019-03,97.52 +Motor fuels,2020-03,139.44 +Furnishings,2020-08,96.36 +Transport services,2020-04,117.37 +Alcohol and tobacco,2020-08,65.20 +Transport services,2019-11,111.40 +Transport services,2019-03,105.94 +Motor fuels,2019-11,107.25 +Motor fuels,2020-06,148.96 +Recreation,2019-08,100.99 +Transport services,2020-08,121.53 +Recreation,2019-12,101.85 +Communication,2020-09,100.19 +Electricity and gas,2019-08,106.93 +Motor fuels,2019-08,108.29 +Alcohol and tobacco,2020-04,63.71 +Furnishings,2019-11,100.06 +Clothing,2020-05,62.72 +Health,2019-11,101.82 +Clothing,2019-03,61.41 +Food,2020-09,125.58 +Food,2020-04,125.71 +Furnishings,2019-06,100.00 +Transport services,2019-12,112.47 +Motor fuels,2019-12,121.45 +Recreation,2019-11,102.44 +Health,2020-09,104.62 +Furnishings,2020-07,96.63 +Health,2020-02,102.44 +Furnishings,2020-01,99.85 +Transport services,2019-08,110.20 +Motor fuels,2020-09,159.09 +Recreation,2020-09,103.09 +Clothing,2019-12,61.55 +Alcohol and tobacco,2020-01,62.56 +Restaurants,2019-04,98.38 +Transport services,2020-09,122.57 +Food,2019-09,126.90 +Food,2020-07,122.51 +Furnishings,2019-09,100.77 +Alcohol and tobacco,2020-03,63.42 +Food,2020-02,126.16 +Electricity and gas,2020-04,98.84 +Motor fuels,2019-09,106.25 +Communication,2019-08,99.93 +Restaurants,2019-06,100.00 +Transport services,2019-07,109.54 +Health,2020-06,103.05 +Restaurants,2019-12,104.01 +Furnishings,2019-12,99.45 +Clothing,2019-06,61.65 +Electricity and gas,2019-10,98.21 +Communication,2019-09,100.47 +Electricity and gas,2020-08,100.13 +Electricity and gas,2019-07,104.86 +Communication,2019-10,100.80 +Recreation,2019-03,98.73 +Communication,2020-04,101.11 +Motor fuels,2020-01,127.89 +Clothing,2020-03,62.69 diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/request.json b/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/request.json new file mode 100644 index 0000000000000000000000000000000000000000..c179e2d4b54859f840866d53335ed84edcb2e630 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/request.json @@ -0,0 +1,5 @@ +{ + "current_month": "2020-07", + "comparison_month": "2019-07", + "weight_reference_month": "2019-06" +} diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/weights.csv b/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/weights.csv new file mode 100644 index 0000000000000000000000000000000000000000..ee9a38218c14d7fdcffeea3cf4cfebb85706f8e8 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0082/environment/workdir/weights.csv @@ -0,0 +1,12 @@ +category,weight,special_group +Transport services,1256.3,other +Electricity and gas,1236.7,energy +Food,2777.8,food +Furnishings,812.8,other +Recreation,1738.7,other +Health,1084.4,other +Restaurants,1808.0,other +Communication,421.3,other +Motor fuels,650.5,energy +Clothing,1106.6,other +Alcohol and tobacco,576.8,other diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0082/instruction.md b/tasks/price-index/price-index-inflation-contributions-d3-t0082/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d51187228962f1cd28430582349f09e4d8e8f71c --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0082/instruction.md @@ -0,0 +1,22 @@ +# Contributions to inflation + +`weights.csv` gives each category's weight as household spending (in millions) in 2019-06, the month the weights refer to; divide by the sum of the weights you are using. It also marks each category as `food`, `energy` or `other`. `indices.csv` gives each category's monthly price index as published, in no particular order and for more months than you need. The published series do not all equal 100 in the same month. First rebase every category so that it equals 100 in 2019-06: rebased index = 100 x published index / published index of the same category in 2019-06. Use the rebased indices everywhere below. + +Compare 2020-07 (the current month) with 2019-07 (the comparison month); both are named in `request.json`. This is a fixed-weight index, so: + +- All-items index in a month = sum(w_i x I_i) / sum(w_i), where w_i is the weight of category i and I_i its index in that month. +- Inflation rate = (all-items index in the current month / all-items index in the comparison month - 1) x 100. +- Contribution of category i = (w_i / sum(w)) x (I_i in the current month - I_i in the comparison month) / (all-items index in the comparison month) x 100. + +Write `answer.json` in this folder, a JSON object with: + +- `all_items_index`: object with the all-items index for the two months, keyed by month (`"2019-07"` and `"2020-07"`), 2 decimals. +- `inflation_percent`: the percentage change of the all-items index from 2019-07 to 2020-07, 2 decimals. +- `contributions`: object keyed by category: its contribution to that change in percentage points, 3 decimals (negative if its prices fell). The contributions add up to the inflation rate. +- `largest_contributor`: the category with the largest contribution. +- `smallest_contributor`: the category with the smallest contribution (the most negative one if any are negative). +- `core_index`: object keyed by the same two months: the index of the core aggregate, which is the categories marked `other` only (no food, no energy), built like the all-items index but with those categories and their weights alone, 2 decimals. +- `core_inflation_percent`: the percentage change of the core index between the two months, 2 decimals. +- `group_contributions`: object with keys `food`, `energy` and `other`: the sum of the contributions (to all-items inflation, as above) of the categories in each group, 3 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0082/solution/oracle.py b/tasks/price-index/price-index-inflation-contributions-d3-t0082/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0082/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-inflation-contributions-d3-t0082/tests/verify.py b/tasks/price-index/price-index-inflation-contributions-d3-t0082/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-inflation-contributions-d3-t0082/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-e0003/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-e0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-e0003/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-e0003/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..1f50ebf42a3c390513f5496d1e18dbc7ad3c02bb --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0003/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2017 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-e0003/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-e0003/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..131828842ea4c10d7f57a64508712400ea6d6ecc --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0003/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2017,software,62466,487.17 +2018,software,61881,530.11 +2019,software,63664,555.05 +2017,bread,43423,410.09 +2018,bread,46626,398.26 +2019,bread,47803,386.67 +2017,vehicles,17401,806.89 +2018,vehicles,19277,835.36 +2019,vehicles,19675,831.34 diff --git a/tasks/price-index/price-index-national-accounts-d1-e0003/instruction.md b/tasks/price-index/price-index-national-accounts-d1-e0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e2a4a396f9a52873cdf2a43b8d7eddefdb330f0 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0003/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2017 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2017"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2017, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2017). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2017). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-e0003/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-e0003/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0003/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-e0003/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-e0003/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0003/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-e0015/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-e0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-e0015/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-e0015/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..39df1bfe5f7a9274869a1c666f7581828a5b20dd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0015/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2019 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-e0015/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-e0015/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..cd44a42f84e6265f4e28f8d9247dca110ea1ecda --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0015/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2019,housing services,42815,161.17 +2020,housing services,42526,170.92 +2021,housing services,43964,173.79 +2019,software,67465,846.01 +2020,software,70974,866.40 +2021,software,73799,891.92 +2019,health care,72671,126.60 +2020,health care,74397,119.04 +2021,health care,76039,118.26 diff --git a/tasks/price-index/price-index-national-accounts-d1-e0015/instruction.md b/tasks/price-index/price-index-national-accounts-d1-e0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb773a5ac73556565324acc339662ca9c45911a2 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0015/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2019 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2019"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2019, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2019). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2019). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-e0015/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-e0015/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0015/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-e0015/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-e0015/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-e0015/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-t0003/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-t0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-t0003/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-t0003/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..39df1bfe5f7a9274869a1c666f7581828a5b20dd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0003/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2019 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-t0003/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-t0003/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..b5a8199474712c05b922a3ceed66cb3aa5283fbd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0003/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2019,vehicles,26050,298.46 +2020,vehicles,26020,322.77 +2021,vehicles,24803,350.46 +2019,clothing,52230,723.74 +2020,clothing,50138,741.62 +2021,clothing,49829,734.77 +2019,electricity to homes,71238,593.09 +2020,electricity to homes,67265,557.88 +2021,electricity to homes,67498,549.62 diff --git a/tasks/price-index/price-index-national-accounts-d1-t0003/instruction.md b/tasks/price-index/price-index-national-accounts-d1-t0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb773a5ac73556565324acc339662ca9c45911a2 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0003/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2019 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2019"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2019, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2019). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2019). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-t0003/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-t0003/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0003/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-t0003/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-t0003/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0003/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-t0015/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-t0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-t0015/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-t0015/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..39df1bfe5f7a9274869a1c666f7581828a5b20dd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0015/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2019 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-t0015/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-t0015/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..b1e219b48ec3458103bc3e8a37fe859a82cb9020 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0015/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2019,housing services,86235,341.80 +2020,housing services,88444,385.38 +2021,housing services,84997,434.95 +2019,electricity to homes,42764,661.47 +2020,electricity to homes,42322,641.40 +2021,electricity to homes,40800,635.05 +2019,software,5410,69.05 +2020,software,5251,69.53 +2021,software,5348,71.03 diff --git a/tasks/price-index/price-index-national-accounts-d1-t0015/instruction.md b/tasks/price-index/price-index-national-accounts-d1-t0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb773a5ac73556565324acc339662ca9c45911a2 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0015/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2019 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2019"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2019, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2019). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2019). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-t0015/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-t0015/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0015/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-t0015/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-t0015/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0015/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-t0027/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-t0027/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0027/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-t0027/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-t0027/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..1f50ebf42a3c390513f5496d1e18dbc7ad3c02bb --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0027/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2017 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-t0027/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-t0027/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..283daa908c7851a078d0fe563b53448cf472db62 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0027/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2017,bread,25613,721.78 +2018,bread,27153,740.09 +2019,bread,28480,816.28 +2017,vehicles,21200,61.05 +2018,vehicles,19877,65.20 +2019,vehicles,20130,69.50 +2017,furniture,41540,827.67 +2018,furniture,40575,857.44 +2019,furniture,39701,848.64 diff --git a/tasks/price-index/price-index-national-accounts-d1-t0027/instruction.md b/tasks/price-index/price-index-national-accounts-d1-t0027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e2a4a396f9a52873cdf2a43b8d7eddefdb330f0 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0027/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2017 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2017"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2017, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2017). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2017). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-t0027/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-t0027/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0027/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-t0027/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-t0027/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0027/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-t0039/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-t0039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0039/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-t0039/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-t0039/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..163385fae18fb29969ff3dd77dda8df015a3f5af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0039/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2008 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-t0039/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-t0039/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..c5a997fa44a38654e01e4e0e26a6e652d071298e --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0039/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2008,machinery,84400,49.36 +2009,machinery,89389,49.86 +2010,machinery,99262,47.77 +2008,health care,50172,594.40 +2009,health care,53088,620.29 +2010,health care,51667,616.50 +2008,software,15436,405.26 +2009,software,15695,432.08 +2010,software,15242,450.30 diff --git a/tasks/price-index/price-index-national-accounts-d1-t0039/instruction.md b/tasks/price-index/price-index-national-accounts-d1-t0039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2767f554520192ea6386ffbed2bbfdb27d0797ea --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0039/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2008 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2008"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2008, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2008). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2008). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-t0039/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-t0039/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0039/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-t0039/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-t0039/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0039/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-t0051/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-t0051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0051/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-t0051/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-t0051/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..031264fe79537838b9be519e7eb976c2c884efcc --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0051/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2014 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-t0051/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-t0051/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..a99f83812f23638a9056b1ea74a2c1ac843d29f6 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0051/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2014,electricity to homes,42916,87.80 +2015,electricity to homes,45573,93.02 +2016,electricity to homes,47308,101.20 +2014,health care,7322,289.50 +2015,health care,7211,279.54 +2016,health care,7269,281.15 +2014,clothing,68152,669.10 +2015,clothing,67033,692.51 +2016,clothing,66801,675.04 diff --git a/tasks/price-index/price-index-national-accounts-d1-t0051/instruction.md b/tasks/price-index/price-index-national-accounts-d1-t0051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c4556db4242a021e2592b3df7b415c0978f3a12f --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0051/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2014 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2014"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2014, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2014). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2014). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-t0051/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-t0051/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0051/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-t0051/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-t0051/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0051/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-t0063/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0063/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-t0063/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-t0063/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..2cee218c55e71db275b9a876ed9394e0bd383b27 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0063/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2010 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-t0063/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-t0063/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..2eab9102742e21a87f36a626ced1c99e59f3f630 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0063/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2010,clothing,5568,730.86 +2011,clothing,5733,787.25 +2012,clothing,5852,815.92 +2010,housing services,51392,471.71 +2011,housing services,50722,487.75 +2012,housing services,53516,489.48 +2010,machinery,71822,662.77 +2011,machinery,70306,673.31 +2012,machinery,69270,728.78 diff --git a/tasks/price-index/price-index-national-accounts-d1-t0063/instruction.md b/tasks/price-index/price-index-national-accounts-d1-t0063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e4a8d4b29c87cc0d38b740763382a3275652c5c1 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0063/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2010 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2010"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2010, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2010). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2010). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-t0063/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-t0063/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0063/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-t0063/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-t0063/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0063/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d1-t0075/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d1-t0075/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0075/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d1-t0075/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d1-t0075/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..54154c0ab29684d6df95b8d48f413a8b62747481 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0075/environment/workdir/accounts.json @@ -0,0 +1,3 @@ +{ + "base_year": 2018 +} diff --git a/tasks/price-index/price-index-national-accounts-d1-t0075/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d1-t0075/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..76a95847a8a1ce2a95af4438d5d5f3e6eefdbc09 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0075/environment/workdir/output.csv @@ -0,0 +1,10 @@ +year,product,quantity,unit_price +2018,machinery,39479,624.75 +2019,machinery,37955,587.69 +2020,machinery,38468,594.20 +2018,software,25792,741.32 +2019,software,25241,693.71 +2020,software,24539,687.01 +2018,health care,51235,396.84 +2019,health care,54448,386.21 +2020,health care,59161,383.35 diff --git a/tasks/price-index/price-index-national-accounts-d1-t0075/instruction.md b/tasks/price-index/price-index-national-accounts-d1-t0075/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd12f39c4869a963437defdbb0b65e34afbbf94c --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0075/instruction.md @@ -0,0 +1,14 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each final good or service in a small economy over 3 years. The base year is 2018 (also in `accounts.json`). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2018"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2018, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2018). + - `inflation_percent`: percentage change of the deflator from the year before, 2 decimals (leave it out for 2018). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d1-t0075/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d1-t0075/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0075/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d1-t0075/tests/verify.py b/tasks/price-index/price-index-national-accounts-d1-t0075/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d1-t0075/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-e0007/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-e0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-e0007/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-e0007/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..51dfe0dab3e29888b08a05998c4564e1eaa409c8 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0007/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2013, + "reference_year": 2011 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-e0007/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-e0007/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..c45123a37e7fddeea9b63ebf3d63d94af0bd1d2f --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0007/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2015,software,final,92283,117.68 +2014,furniture,final,33694,527.43 +2015,furniture,final,33082,563.87 +2014,flour,intermediate,25219,790.44 +2011,furniture,final,28917,420.34 +2012,vehicles,final,41901,762.64 +2011,flour,intermediate,24812,793.39 +2011,raw timber,intermediate,38645,556.23 +2013,raw timber,intermediate,38510,509.38 +2014,vehicles,final,38291,859.12 +2011,vehicles,final,42569,765.94 +2012,furniture,final,30806,433.39 +2015,housing services,final,20431,647.71 +2014,machinery,final,26473,269.94 +2011,software,final,84838,113.19 +2014,housing services,final,20575,628.35 +2015,machinery,final,29022,274.78 +2011,machinery,final,25096,217.44 +2012,flour,intermediate,25538,764.60 +2015,flour,intermediate,27347,830.48 +2014,software,final,90186,116.43 +2012,machinery,final,27148,230.28 +2011,housing services,final,19082,571.92 +2013,software,final,90442,119.66 +2014,raw timber,intermediate,36858,531.66 +2012,housing services,final,19253,584.33 +2012,software,final,84762,112.03 +2013,vehicles,final,40425,803.32 +2013,housing services,final,19413,604.17 +2015,vehicles,final,37558,897.10 +2013,furniture,final,33007,483.54 +2012,raw timber,intermediate,37097,533.76 +2013,machinery,final,26580,247.45 +2015,raw timber,intermediate,37204,537.60 +2013,flour,intermediate,25218,762.91 diff --git a/tasks/price-index/price-index-national-accounts-d2-e0007/instruction.md b/tasks/price-index/price-index-national-accounts-d2-e0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6a34fdf79d48954d8b0a0afcfbedf6506b363dc4 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0007/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2013 and the reference year of the chain-linked index is 2011 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2011) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2011"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2013, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2011 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2011). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2011). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-e0007/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-e0007/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0007/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-e0007/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-e0007/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0007/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-e0019/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-e0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-e0019/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-e0019/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..06805b46b89e722a8f49270c129e3ef2407961a7 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0019/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2014, + "reference_year": 2014 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-e0019/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-e0019/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0c462a8700d35b09d034f34ac7a68d2af126534 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0019/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2016,housing services,final,59259,55.30 +2017,cotton yarn,intermediate,59436,279.34 +2016,vehicles,final,47914,955.43 +2015,bread,final,4262,468.02 +2016,restaurant meals,final,61717,647.03 +2015,vehicles,final,46749,907.92 +2017,housing services,final,61537,59.15 +2018,vehicles,final,44811,1136.56 +2014,housing services,final,56503,49.38 +2017,vehicles,final,46119,1051.28 +2017,health care,final,25618,561.73 +2016,bread,final,3999,474.10 +2018,bread,final,3811,511.14 +2018,housing services,final,65371,64.43 +2018,flour,intermediate,6297,608.25 +2015,health care,final,25128,629.99 +2015,cotton yarn,intermediate,58981,266.88 +2017,bread,final,3779,506.48 +2017,flour,intermediate,6068,637.38 +2018,health care,final,26087,529.18 +2015,flour,intermediate,5903,657.89 +2014,health care,final,26327,670.82 +2018,cotton yarn,intermediate,55976,293.81 +2014,flour,intermediate,5965,689.09 +2016,cotton yarn,intermediate,59187,274.41 +2017,restaurant meals,final,56460,659.07 +2014,bread,final,4488,449.70 +2014,vehicles,final,45798,839.92 +2018,restaurant meals,final,55341,671.55 +2015,housing services,final,57166,51.17 +2014,cotton yarn,intermediate,59683,251.43 +2016,health care,final,24616,599.75 +2015,restaurant meals,final,65509,645.62 +2014,restaurant meals,final,67812,625.87 +2016,flour,intermediate,6130,631.25 diff --git a/tasks/price-index/price-index-national-accounts-d2-e0019/instruction.md b/tasks/price-index/price-index-national-accounts-d2-e0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00837254767c07513ab47f00170f591a7449cb3a --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0019/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2014 and the reference year of the chain-linked index is 2014 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2014) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2014"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2014, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2014 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2014). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2014). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-e0019/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-e0019/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0019/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-e0019/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-e0019/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-e0019/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-t0007/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-t0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-t0007/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-t0007/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..eec3a9acc6aa1afa027222c00eb51b97acc59173 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0007/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2016, + "reference_year": 2012 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-t0007/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-t0007/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..7d651438a43237eb0904072971ff48bd7fe1bcac --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0007/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2012,flour,intermediate,61187,566.98 +2014,vehicles,final,75484,896.18 +2013,restaurant meals,final,54503,630.96 +2013,electricity to homes,final,28529,781.08 +2013,machinery,final,36039,543.74 +2012,steel,intermediate,87384,193.09 +2016,bread,final,40104,677.18 +2016,electricity to homes,final,27767,807.53 +2014,steel,intermediate,88088,230.67 +2013,vehicles,final,67354,917.24 +2014,flour,intermediate,61003,689.25 +2015,electricity to homes,final,26671,782.85 +2016,flour,intermediate,62257,839.68 +2012,vehicles,final,61848,889.39 +2014,electricity to homes,final,27810,784.52 +2015,flour,intermediate,61717,773.47 +2015,machinery,final,38349,671.98 +2013,bread,final,40437,570.95 +2016,vehicles,final,78655,943.12 +2016,restaurant meals,final,57396,653.97 +2013,flour,intermediate,62834,625.04 +2012,restaurant meals,final,54814,624.78 +2012,machinery,final,36369,512.50 +2014,machinery,final,36755,604.73 +2014,restaurant meals,final,53487,642.05 +2013,steel,intermediate,87678,206.96 +2015,bread,final,41705,655.27 +2016,machinery,final,40634,709.10 +2012,bread,final,39990,551.93 +2015,restaurant meals,final,55081,633.63 +2014,bread,final,40233,616.03 +2015,steel,intermediate,89524,239.66 +2012,electricity to homes,final,28600,767.99 +2016,steel,intermediate,97354,257.08 +2015,vehicles,final,76585,911.03 diff --git a/tasks/price-index/price-index-national-accounts-d2-t0007/instruction.md b/tasks/price-index/price-index-national-accounts-d2-t0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..da476d68741ae68f017250b95f99ea7a8bdcdf0a --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0007/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2016 and the reference year of the chain-linked index is 2012 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2012) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2012"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2016, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2012 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2012). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2012). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-t0007/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-t0007/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0007/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-t0007/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-t0007/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0007/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-t0019/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-t0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-t0019/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-t0019/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..0697321300277b842226ca4fbe1962a8ad0fb5a6 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0019/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2015, + "reference_year": 2012 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-t0019/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-t0019/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..103884df5fe6d5bb2d80493262c4239da0947f9a --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0019/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2016,software,final,37676,820.36 +2014,housing services,final,23205,277.73 +2013,software,final,40526,724.19 +2015,vehicles,final,45039,123.51 +2016,bread,final,5690,102.36 +2013,raw timber,intermediate,54663,269.85 +2013,housing services,final,22222,254.81 +2012,housing services,final,22848,232.94 +2013,bread,final,5047,94.01 +2016,housing services,final,23361,329.50 +2014,cotton yarn,intermediate,55706,191.08 +2015,electricity to homes,final,19853,97.49 +2012,cotton yarn,intermediate,45635,185.37 +2015,housing services,final,22937,298.24 +2015,raw timber,intermediate,59160,286.68 +2015,bread,final,5545,97.50 +2012,raw timber,intermediate,55458,250.64 +2014,software,final,38365,752.94 +2012,bread,final,4677,89.84 +2016,cotton yarn,intermediate,61449,177.76 +2014,vehicles,final,40699,117.79 +2016,raw timber,intermediate,62446,300.03 +2016,vehicles,final,48594,137.43 +2015,cotton yarn,intermediate,57254,184.91 +2015,software,final,39269,807.91 +2012,electricity to homes,final,16696,74.18 +2012,vehicles,final,37698,107.42 +2013,electricity to homes,final,17639,82.18 +2013,vehicles,final,39735,112.76 +2014,bread,final,5338,100.30 +2016,electricity to homes,final,21018,108.92 +2014,electricity to homes,final,19005,91.64 +2013,cotton yarn,intermediate,50142,195.14 +2012,software,final,40998,664.40 +2014,raw timber,intermediate,56948,272.21 diff --git a/tasks/price-index/price-index-national-accounts-d2-t0019/instruction.md b/tasks/price-index/price-index-national-accounts-d2-t0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..93ae61d03f3e5afb93c334642646b9ef4b5f8787 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0019/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2015 and the reference year of the chain-linked index is 2012 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2012) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2012"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2015, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2012 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2012). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2012). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-t0019/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-t0019/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0019/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-t0019/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-t0019/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0019/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-t0031/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-t0031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0031/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-t0031/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-t0031/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..5688f686eb06be707ac5bc104cbce030d6806548 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0031/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2012, + "reference_year": 2009 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-t0031/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-t0031/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..c4304337f6e1564ecfd0df89f2656d74b097cea8 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0031/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2010,vehicles,final,46090,722.53 +2013,machinery,final,48396,181.99 +2011,health care,final,84394,100.88 +2011,electricity to homes,final,81575,806.03 +2012,health care,final,85668,100.52 +2009,vehicles,final,45921,749.06 +2011,vehicles,final,47322,736.99 +2013,health care,final,84043,105.22 +2010,electricity to homes,final,80925,795.31 +2012,electricity to homes,final,83218,817.51 +2010,flour,intermediate,6534,378.74 +2011,flour,intermediate,6333,393.08 +2010,machinery,final,51342,172.91 +2012,vehicles,final,49046,708.87 +2010,health care,final,85322,101.12 +2011,machinery,final,49258,182.50 +2012,flour,intermediate,5925,415.08 +2009,health care,final,86758,97.96 +2013,housing services,final,62537,790.74 +2009,electricity to homes,final,75301,772.73 +2012,machinery,final,47967,184.04 +2011,housing services,final,62585,661.87 +2012,cotton yarn,intermediate,26040,281.16 +2012,housing services,final,59249,724.81 +2013,cotton yarn,intermediate,26621,270.97 +2013,vehicles,final,49354,725.84 +2010,cotton yarn,intermediate,26429,274.94 +2010,housing services,final,64697,637.93 +2013,flour,intermediate,5574,439.22 +2009,machinery,final,52391,170.97 +2011,cotton yarn,intermediate,26049,280.27 +2009,flour,intermediate,6936,382.43 +2009,cotton yarn,intermediate,26488,275.59 +2013,electricity to homes,final,89758,785.79 +2009,housing services,final,67404,586.40 diff --git a/tasks/price-index/price-index-national-accounts-d2-t0031/instruction.md b/tasks/price-index/price-index-national-accounts-d2-t0031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4efc5f936610535c1a4b7a101a9ed87e068dd02d --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0031/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2012 and the reference year of the chain-linked index is 2009 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2009) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2009"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2012, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2009 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2009). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2009). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-t0031/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-t0031/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0031/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-t0031/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-t0031/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0031/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-t0043/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-t0043/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0043/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-t0043/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-t0043/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..f710e972200b45e86e0a83ca507d600f0b333ccc --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0043/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2017, + "reference_year": 2013 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-t0043/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-t0043/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..2ce5b8a3524ad6fd95b54a86a7fd51b6643a7561 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0043/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2016,raw timber,intermediate,5627,163.90 +2017,raw timber,intermediate,5774,167.58 +2013,clothing,final,20801,507.95 +2015,vehicles,final,38110,357.07 +2015,restaurant meals,final,88738,432.15 +2016,furniture,final,50276,246.69 +2017,restaurant meals,final,81311,487.14 +2014,restaurant meals,final,87842,437.69 +2014,clothing,final,21347,507.75 +2013,vehicles,final,39898,347.28 +2014,furniture,final,48525,248.30 +2017,furniture,final,49972,262.14 +2014,flour,intermediate,64373,529.73 +2015,clothing,final,22330,506.88 +2017,flour,intermediate,88237,541.35 +2015,bread,final,11186,747.39 +2015,flour,intermediate,71895,546.52 +2015,raw timber,intermediate,5339,163.84 +2014,vehicles,final,39410,348.37 +2016,clothing,final,21616,486.02 +2016,vehicles,final,39457,373.25 +2013,furniture,final,48746,255.68 +2014,bread,final,10609,688.86 +2016,restaurant meals,final,84069,461.28 +2017,clothing,final,22483,477.53 +2013,raw timber,intermediate,4905,158.52 +2013,restaurant meals,final,84698,432.46 +2013,flour,intermediate,63488,501.35 +2015,furniture,final,47229,243.52 +2014,raw timber,intermediate,5162,163.41 +2017,bread,final,12914,783.41 +2016,bread,final,12090,765.59 +2017,vehicles,final,38359,379.78 +2013,bread,final,9637,641.70 +2016,flour,intermediate,80448,539.19 diff --git a/tasks/price-index/price-index-national-accounts-d2-t0043/instruction.md b/tasks/price-index/price-index-national-accounts-d2-t0043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1547953c7edfea4cf3f10eefcc5e6eb4747bcc05 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0043/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2017 and the reference year of the chain-linked index is 2013 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2013) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2013"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2017, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2013 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2013). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2013). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-t0043/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-t0043/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0043/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-t0043/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-t0043/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0043/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-t0055/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-t0055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0055/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-t0055/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-t0055/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..7cdc2a054505c7bfec6ff88ff396bf58b971c927 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0055/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2016, + "reference_year": 2015 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-t0055/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-t0055/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..8f5ec069620643f6694e3f772e9a512066cc1fdc --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0055/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2019,restaurant meals,final,71690,258.06 +2015,bread,final,82303,364.19 +2016,housing services,final,19717,232.79 +2018,furniture,final,35758,458.03 +2019,flour,intermediate,30332,814.33 +2019,bread,final,114559,346.48 +2018,housing services,final,19298,279.66 +2016,cotton yarn,intermediate,22524,485.05 +2018,restaurant meals,final,68613,248.02 +2016,bread,final,90056,376.98 +2015,housing services,final,19856,225.06 +2017,housing services,final,19050,257.07 +2015,flour,intermediate,23079,720.64 +2019,furniture,final,35306,480.75 +2017,vehicles,final,65730,489.09 +2018,vehicles,final,70471,499.45 +2015,cotton yarn,intermediate,21779,480.10 +2017,bread,final,94258,354.53 +2019,cotton yarn,intermediate,24501,563.05 +2016,vehicles,final,62191,474.87 +2018,bread,final,104823,338.16 +2017,flour,intermediate,26999,777.47 +2017,cotton yarn,intermediate,22416,536.60 +2019,vehicles,final,72505,504.84 +2015,restaurant meals,final,68038,228.25 +2015,furniture,final,37031,408.39 +2017,furniture,final,35062,466.50 +2018,flour,intermediate,29158,814.17 +2016,furniture,final,37210,438.87 +2018,cotton yarn,intermediate,22553,542.36 +2019,housing services,final,19472,281.59 +2016,restaurant meals,final,70096,233.49 +2016,flour,intermediate,24591,747.24 +2017,restaurant meals,final,73103,235.07 +2015,vehicles,final,62160,485.05 diff --git a/tasks/price-index/price-index-national-accounts-d2-t0055/instruction.md b/tasks/price-index/price-index-national-accounts-d2-t0055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3264e9a7220e671818304701aa5cd5de4351d474 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0055/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2016 and the reference year of the chain-linked index is 2015 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2015) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2015"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2016, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2015 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2015). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2015). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-t0055/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-t0055/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0055/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-t0055/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-t0055/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0055/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-t0067/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-t0067/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0067/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-t0067/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-t0067/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..faa5a7043bbac29a674bad9a7da5274980856aaf --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0067/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2020, + "reference_year": 2017 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-t0067/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-t0067/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..5d594876497982682edcf528f0a94b9e6e4e68ee --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0067/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2018,cotton yarn,intermediate,86578,528.28 +2019,restaurant meals,final,1359,122.34 +2020,furniture,final,49918,968.54 +2017,flour,intermediate,35161,694.15 +2018,software,final,90985,587.22 +2019,software,final,89218,620.08 +2019,clothing,final,43564,645.33 +2018,furniture,final,45433,826.17 +2017,cotton yarn,intermediate,84314,518.46 +2019,cotton yarn,intermediate,82401,535.68 +2017,clothing,final,40552,605.77 +2020,software,final,95582,659.39 +2021,clothing,final,42296,637.21 +2019,housing services,final,27840,659.35 +2021,restaurant meals,final,1390,116.50 +2020,clothing,final,41468,654.59 +2021,housing services,final,30639,712.67 +2020,flour,intermediate,40760,684.09 +2021,software,final,103033,698.51 +2017,housing services,final,27366,558.47 +2018,flour,intermediate,35275,695.98 +2017,software,final,88352,593.50 +2019,furniture,final,47405,929.68 +2020,housing services,final,30182,660.64 +2021,furniture,final,53394,1095.41 +2020,cotton yarn,intermediate,81597,539.41 +2021,flour,intermediate,41896,663.15 +2020,restaurant meals,final,1349,117.80 +2021,cotton yarn,intermediate,81989,516.60 +2018,clothing,final,42414,632.00 +2019,flour,intermediate,37917,689.21 +2018,restaurant meals,final,1246,120.85 +2017,restaurant meals,final,1191,119.44 +2018,housing services,final,27486,610.46 +2017,furniture,final,43941,777.16 diff --git a/tasks/price-index/price-index-national-accounts-d2-t0067/instruction.md b/tasks/price-index/price-index-national-accounts-d2-t0067/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b270730f3f9e58b9a060592e371528204270f545 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0067/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2020 and the reference year of the chain-linked index is 2017 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2017) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2017"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2020, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2017 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2017). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2017). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-t0067/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-t0067/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0067/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-t0067/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-t0067/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0067/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d2-t0079/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d2-t0079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0079/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d2-t0079/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d2-t0079/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..0697321300277b842226ca4fbe1962a8ad0fb5a6 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0079/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2015, + "reference_year": 2012 +} diff --git a/tasks/price-index/price-index-national-accounts-d2-t0079/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d2-t0079/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..74cc2a6ef7c6a914742e3e122112dd4db6d7c04c --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0079/environment/workdir/output.csv @@ -0,0 +1,36 @@ +year,product,use,quantity,unit_price +2012,steel,intermediate,18795,278.43 +2015,steel,intermediate,17762,306.14 +2014,furniture,final,24127,689.61 +2016,restaurant meals,final,3701,1169.02 +2015,flour,intermediate,27637,149.45 +2014,machinery,final,6438,430.40 +2016,electricity to homes,final,38333,873.62 +2012,machinery,final,6960,407.15 +2013,flour,intermediate,25100,135.47 +2014,electricity to homes,final,35565,743.77 +2016,software,final,98494,655.67 +2015,furniture,final,25735,656.70 +2016,furniture,final,25900,660.92 +2016,flour,intermediate,29587,147.44 +2014,software,final,96484,654.53 +2013,restaurant meals,final,3091,894.88 +2013,steel,intermediate,18377,291.25 +2015,software,final,95439,677.89 +2014,flour,intermediate,26274,144.37 +2012,restaurant meals,final,2940,841.06 +2013,machinery,final,6804,427.40 +2014,steel,intermediate,18115,292.54 +2013,electricity to homes,final,34370,692.16 +2014,restaurant meals,final,3368,1005.04 +2015,electricity to homes,final,35105,792.47 +2016,machinery,final,6467,459.59 +2012,furniture,final,23542,732.68 +2016,steel,intermediate,17286,320.73 +2012,software,final,86169,624.60 +2015,machinery,final,6359,438.22 +2012,flour,intermediate,24468,130.05 +2013,software,final,93581,643.85 +2015,restaurant meals,final,3494,1060.70 +2013,furniture,final,23963,721.91 +2012,electricity to homes,final,31810,670.58 diff --git a/tasks/price-index/price-index-national-accounts-d2-t0079/instruction.md b/tasks/price-index/price-index-national-accounts-d2-t0079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..93ae61d03f3e5afb93c334642646b9ef4b5f8787 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0079/instruction.md @@ -0,0 +1,20 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2015 and the reference year of the chain-linked index is 2012 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2012) = 100, and index(t) = index(t-1) x link(t) for each later year. + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2012"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2015, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2012 = 100, 2 decimals. + - `real_growth_percent`: percentage change of real GDP from the year before, 2 decimals (leave it out for 2012). + - `chain_growth_percent`: percentage change of the chain-linked index from the year before, 2 decimals (leave it out for 2012). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d2-t0079/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d2-t0079/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0079/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d2-t0079/tests/verify.py b/tasks/price-index/price-index-national-accounts-d2-t0079/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d2-t0079/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-e0011/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-e0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..b47f2217df5d8e1884d33281f398a8333a85b4d4 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2014, + "reference_year": 2013 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..9fc90f7cb04f4d3c88d18f5e1a368bb3bebcbeec --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2011,furniture,final,14423,284.46 +2014,software,final,85413,116.90 +2012,clothing,final,29035,238.05 +2013,vehicles,final,18068,144.30 +2012,furniture,final,14319,308.05 +2012,software,final,80895,109.30 +2015,housing services,final,17259,30.70 +2015,clothing,final,39857,264.59 +2015,bread,final,16440,430.58 +2014,vehicles,final,18629,155.52 +2011,housing services,final,15231,21.92 +2014,housing services,final,17017,29.62 +2012,electricity to factories,intermediate,67200,8.16 +2013,bread,final,17060,440.34 +2015,raw timber,intermediate,57269,702.18 +2014,raw timber,intermediate,55008,673.80 +2013,raw timber,intermediate,55256,655.98 +2014,flour,intermediate,68789,957.14 +2011,raw timber,intermediate,46301,587.72 +2012,flour,intermediate,64248,835.51 +2014,bread,final,16217,454.26 +2013,software,final,81071,115.73 +2013,electricity to factories,intermediate,73935,8.47 +2013,housing services,final,16917,26.51 +2012,housing services,final,16715,23.65 +2014,electricity to factories,intermediate,75117,8.71 +2013,flour,intermediate,65250,899.05 +2014,furniture,final,15545,349.52 +2015,furniture,final,15870,382.56 +2013,furniture,final,15291,323.88 +2011,clothing,final,27773,224.31 +2011,bread,final,17237,428.45 +2015,vehicles,final,19014,156.81 +2011,software,final,79000,111.83 +2011,flour,intermediate,59331,787.75 +2012,vehicles,final,18662,141.12 +2014,clothing,final,36074,262.52 +2015,flour,intermediate,67079,1034.65 +2011,vehicles,final,19657,130.78 +2015,software,final,91326,113.83 +2013,clothing,final,32415,245.13 +2012,raw timber,intermediate,51065,638.42 +2015,electricity to factories,intermediate,80718,8.65 +2011,electricity to factories,intermediate,66252,8.10 +2012,bread,final,17098,444.69 diff --git a/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..26df552fef9e6841d0342a6107aa46fcdb5fae93 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0011/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2011,12383 +2013,12682 +2012,12532 +2014,12795 +2015,12744 diff --git a/tasks/price-index/price-index-national-accounts-d3-e0011/instruction.md b/tasks/price-index/price-index-national-accounts-d3-e0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb3243c507fd1861abcc6100d17bc62c16a64adb --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0011/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2014 and the reference year of the chain-linked index is 2013 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2013) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2013 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2011"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2014, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2013 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2013 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2014 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2011 to 2015, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-e0011/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-e0011/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0011/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-e0011/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-e0011/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0011/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-e0023/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-e0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..6ebc025ecec59a6c8be53072de153d6512107e42 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2011, + "reference_year": 2012 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..feb75bd7c9f085ca67ac77d316d9178a25b1a19c --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2013,electricity to factories,intermediate,41599,1142.71 +2011,bread,final,10218,195.03 +2011,electricity to factories,intermediate,41737,962.02 +2014,health care,final,4665,1091.82 +2011,raw timber,intermediate,75924,105.89 +2010,furniture,final,14228,836.18 +2012,electricity to homes,final,11637,299.05 +2012,electricity to factories,intermediate,40837,1021.93 +2011,vehicles,final,83918,128.55 +2014,electricity to factories,intermediate,41772,1204.83 +2010,raw timber,intermediate,73412,108.01 +2013,furniture,final,16127,846.17 +2013,electricity to homes,final,11524,315.20 +2014,electricity to homes,final,11722,338.26 +2011,health care,final,5356,894.66 +2013,bread,final,9663,219.09 +2011,steel,intermediate,69218,566.13 +2010,electricity to homes,final,11018,258.24 +2013,raw timber,intermediate,83126,108.49 +2014,raw timber,intermediate,86825,108.37 +2014,steel,intermediate,89273,610.36 +2012,software,final,76823,15.25 +2013,health care,final,5094,1062.27 +2010,bread,final,10258,173.14 +2013,steel,intermediate,82395,622.25 +2013,software,final,76829,15.35 +2014,bread,final,9884,246.13 +2012,raw timber,intermediate,81024,107.50 +2013,vehicles,final,99843,131.42 +2014,software,final,77464,16.23 +2012,bread,final,10129,212.20 +2012,health care,final,5032,971.23 +2014,vehicles,final,111355,130.51 +2014,furniture,final,16643,888.05 +2010,electricity to factories,intermediate,40890,883.34 +2010,health care,final,5512,877.71 +2012,furniture,final,14892,853.80 +2010,software,final,87093,15.35 +2011,furniture,final,14938,876.96 +2011,software,final,82019,15.42 +2010,steel,intermediate,65936,552.49 +2010,vehicles,final,78128,123.02 +2012,vehicles,final,89970,131.38 +2012,steel,intermediate,75126,597.45 +2011,electricity to homes,final,11560,273.32 diff --git a/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..17b05ff1147a2895498a7d87b8b9684f715bf6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0023/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2011,19896 +2014,20207 +2013,19912 +2010,19785 +2012,19842 diff --git a/tasks/price-index/price-index-national-accounts-d3-e0023/instruction.md b/tasks/price-index/price-index-national-accounts-d3-e0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6be230ee025e1c3da35c4d46896830c4e2b13210 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0023/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2011 and the reference year of the chain-linked index is 2012 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2012) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2012 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2010"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2011, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2012 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2012 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2011 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2010 to 2014, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-e0023/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-e0023/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0023/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-e0023/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-e0023/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-e0023/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-t0011/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-t0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..b98e5736cfcbb925ac872026156f2f07c57d980b --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2011, + "reference_year": 2010 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..935efc547051579603933529dc729c93831be86d --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2011,electricity to homes,final,48257,589.15 +2011,flour,intermediate,20109,389.82 +2009,flour,intermediate,19240,339.88 +2013,flour,intermediate,19951,447.02 +2009,machinery,final,84988,32.57 +2009,software,final,21199,656.73 +2011,raw timber,intermediate,32315,210.54 +2012,raw timber,intermediate,31764,223.14 +2012,machinery,final,82899,35.03 +2010,machinery,final,88122,32.85 +2013,software,final,25478,828.56 +2009,electricity to homes,final,39627,521.94 +2011,vehicles,final,14201,593.14 +2011,steel,intermediate,36509,767.75 +2012,flour,intermediate,20250,406.79 +2010,health care,final,39602,33.54 +2013,raw timber,intermediate,32106,217.18 +2010,software,final,21360,707.24 +2013,steel,intermediate,39364,831.17 +2012,clothing,final,20725,934.32 +2011,health care,final,39023,33.99 +2012,health care,final,39825,35.60 +2012,electricity to homes,final,47860,601.20 +2013,clothing,final,21842,999.33 +2013,machinery,final,80488,36.29 +2010,steel,intermediate,35435,748.98 +2010,flour,intermediate,19599,362.41 +2010,raw timber,intermediate,30423,210.55 +2013,electricity to homes,final,50922,628.14 +2011,software,final,22992,737.86 +2011,machinery,final,82561,34.29 +2013,health care,final,40582,36.52 +2013,vehicles,final,13984,642.14 +2009,raw timber,intermediate,30885,204.41 +2011,clothing,final,20912,905.67 +2009,clothing,final,20716,874.75 +2009,health care,final,38622,33.73 +2009,steel,intermediate,32811,709.76 +2012,vehicles,final,14354,638.58 +2012,software,final,24307,777.40 +2010,electricity to homes,final,43554,563.95 +2012,steel,intermediate,39131,785.27 +2010,clothing,final,21069,894.83 +2009,vehicles,final,14037,508.41 +2010,vehicles,final,14592,551.74 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..584b9955ad6fe0a58b5155729e239272d99c97d0 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0011/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2013,14115 +2012,14181 +2010,13818 +2011,14047 +2009,13549 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0011/instruction.md b/tasks/price-index/price-index-national-accounts-d3-t0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..259b45419e27fe0a07b4c843348f30988cf7d8cc --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0011/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2011 and the reference year of the chain-linked index is 2010 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2010) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2010 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2009"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2011, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2010 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2010 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2011 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2009 to 2013, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-t0011/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-t0011/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0011/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-t0011/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-t0011/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0011/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-t0023/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-t0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..a1c0dd0149f2a21ad022f468308f5fdb37073374 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2018, + "reference_year": 2016 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..a47d5b2989cea11f3a7c39354040bbeb2839d325 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2018,health care,final,44369,471.71 +2017,restaurant meals,final,17729,182.44 +2017,flour,intermediate,74435,881.13 +2019,cotton yarn,intermediate,47135,1028.15 +2016,raw timber,intermediate,5209,366.43 +2016,bread,final,57032,771.17 +2019,clothing,final,50844,113.82 +2019,health care,final,46093,455.65 +2016,clothing,final,47630,100.90 +2018,bread,final,55656,753.64 +2017,cotton yarn,intermediate,53275,971.75 +2018,housing services,final,9625,792.67 +2017,bread,final,57555,750.28 +2018,machinery,final,41708,720.43 +2016,flour,intermediate,73602,836.75 +2015,flour,intermediate,72114,809.44 +2019,raw timber,intermediate,5508,337.92 +2017,housing services,final,9002,815.11 +2018,restaurant meals,final,17939,177.90 +2016,health care,final,41982,497.11 +2016,cotton yarn,intermediate,53692,923.27 +2019,flour,intermediate,71262,1001.94 +2019,machinery,final,39923,728.06 +2019,bread,final,54208,772.78 +2018,clothing,final,50696,110.34 +2017,raw timber,intermediate,5215,346.09 +2016,housing services,final,8633,807.86 +2018,cotton yarn,intermediate,48821,995.23 +2015,machinery,final,45397,786.03 +2016,machinery,final,45679,755.37 +2018,raw timber,intermediate,5253,353.29 +2018,flour,intermediate,70611,939.42 +2015,housing services,final,8195,837.74 +2015,health care,final,41657,498.72 +2019,housing services,final,10313,765.35 +2015,cotton yarn,intermediate,57163,893.81 +2015,raw timber,intermediate,5290,355.88 +2016,restaurant meals,final,18178,182.02 +2015,bread,final,54114,749.15 +2017,health care,final,42212,483.56 +2015,clothing,final,47136,100.78 +2015,restaurant meals,final,17117,187.60 +2017,machinery,final,43469,718.33 +2019,restaurant meals,final,18905,178.59 +2017,clothing,final,47772,106.01 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..5ae7462bf38dc8d577c3b408b2e14368dfd2b9a6 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0023/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2017,19572 +2016,19416 +2018,19945 +2015,19182 +2019,19974 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0023/instruction.md b/tasks/price-index/price-index-national-accounts-d3-t0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d38b2da6c56007582955e8f9f57b9fc2c6efc38 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0023/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2018 and the reference year of the chain-linked index is 2016 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2016) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2016 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2015"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2018, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2016 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2016 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2018 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2015 to 2019, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-t0023/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-t0023/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0023/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-t0023/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-t0023/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0023/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-t0035/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-t0035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0035/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..6113be21879f96262c6b0cb279bab576512b99f2 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2020, + "reference_year": 2019 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..820b5db2b8fb0d7ee81fd230bd042cdc8276255e --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2021,bread,final,15663,817.84 +2017,electricity to factories,intermediate,76832,842.56 +2021,electricity to homes,final,64443,818.03 +2018,steel,intermediate,52896,36.80 +2020,software,final,19832,861.80 +2017,electricity to homes,final,49443,712.08 +2017,software,final,19710,751.38 +2020,flour,intermediate,60445,173.24 +2021,software,final,20136,914.15 +2021,electricity to factories,intermediate,95269,959.94 +2021,flour,intermediate,59704,175.64 +2020,restaurant meals,final,102015,295.25 +2019,housing services,final,44311,179.28 +2020,steel,intermediate,52738,41.48 +2019,machinery,final,71938,43.59 +2018,electricity to factories,intermediate,83446,914.60 +2017,flour,intermediate,63955,185.38 +2018,bread,final,12959,775.44 +2020,bread,final,15312,793.14 +2017,machinery,final,70632,44.80 +2021,steel,intermediate,51508,42.59 +2018,machinery,final,73065,43.80 +2018,electricity to homes,final,52099,716.99 +2019,restaurant meals,final,97876,271.97 +2019,flour,intermediate,60070,181.98 +2018,software,final,20085,790.06 +2020,housing services,final,45620,176.73 +2017,bread,final,12637,738.25 +2019,electricity to homes,final,56633,768.93 +2019,bread,final,13967,779.65 +2019,electricity to factories,intermediate,88619,927.24 +2021,housing services,final,47927,186.82 +2019,software,final,20149,820.16 +2021,restaurant meals,final,113178,297.40 +2018,restaurant meals,final,91793,272.66 +2017,steel,intermediate,51384,35.43 +2018,flour,intermediate,59434,184.01 +2017,housing services,final,42271,173.00 +2020,machinery,final,71909,42.99 +2021,machinery,final,71686,41.34 +2020,electricity to factories,intermediate,91635,950.51 +2019,steel,intermediate,51619,39.40 +2020,electricity to homes,final,58817,768.78 +2017,restaurant meals,final,85240,252.45 +2018,housing services,final,42934,177.41 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..a2f1add060becdcae960675d0bb8a289951f347a --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0035/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2020,8688 +2019,8604 +2018,8483 +2021,8646 +2017,8451 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0035/instruction.md b/tasks/price-index/price-index-national-accounts-d3-t0035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2eb0de04c96ac7a16a1ef5c1d6c5e846fc362334 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0035/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2020 and the reference year of the chain-linked index is 2019 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2019) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2019 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2017"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2020, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2019 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2019 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2020 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2017 to 2021, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-t0035/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-t0035/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0035/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-t0035/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-t0035/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0035/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-t0047/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-t0047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0047/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..6113be21879f96262c6b0cb279bab576512b99f2 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2020, + "reference_year": 2019 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..b2a2c810687e51f90766ed2c7dea0477d25e4d28 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2020,machinery,final,76459,281.58 +2018,clothing,final,59277,686.04 +2022,flour,intermediate,39029,318.67 +2019,clothing,final,60039,723.73 +2019,health care,final,11733,259.95 +2021,software,final,48362,425.28 +2022,restaurant meals,final,59271,672.48 +2018,software,final,47952,403.91 +2020,health care,final,10976,265.77 +2018,restaurant meals,final,61176,661.62 +2019,furniture,final,44855,19.14 +2019,machinery,final,76136,283.13 +2019,cotton yarn,intermediate,69321,510.02 +2020,software,final,48851,409.88 +2021,clothing,final,61124,821.49 +2018,electricity to factories,intermediate,21430,897.65 +2018,furniture,final,45314,17.93 +2020,furniture,final,45489,20.26 +2021,restaurant meals,final,59590,663.03 +2021,health care,final,11088,277.56 +2019,electricity to factories,intermediate,21803,952.16 +2022,furniture,final,47620,22.12 +2022,machinery,final,75915,286.89 +2019,software,final,50992,396.07 +2021,machinery,final,78559,287.49 +2018,health care,final,12369,243.63 +2018,machinery,final,73148,273.67 +2020,cotton yarn,intermediate,71054,521.64 +2022,software,final,51238,431.02 +2022,clothing,final,58370,854.70 +2018,cotton yarn,intermediate,67922,482.99 +2019,restaurant meals,final,62877,645.61 +2022,electricity to factories,intermediate,20819,930.46 +2021,cotton yarn,intermediate,72505,553.12 +2019,flour,intermediate,39129,285.38 +2022,cotton yarn,intermediate,72201,546.69 +2020,electricity to factories,intermediate,21403,925.45 +2020,restaurant meals,final,60806,671.25 +2021,furniture,final,46307,20.83 +2020,flour,intermediate,39431,289.69 +2021,flour,intermediate,38950,292.41 +2020,clothing,final,63262,750.46 +2021,electricity to factories,intermediate,20695,937.70 +2018,flour,intermediate,38250,266.82 +2022,health care,final,10294,282.77 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..bab42e4fe2e9305cf263fb4ab3d4731538078347 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0047/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2019,8057 +2021,8196 +2020,8092 +2018,8060 +2022,8219 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0047/instruction.md b/tasks/price-index/price-index-national-accounts-d3-t0047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27e24a006e77dc898daee6d8d499b0b6116f4a84 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0047/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2020 and the reference year of the chain-linked index is 2019 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2019) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2019 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2018"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2020, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2019 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2019 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2020 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2018 to 2022, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-t0047/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-t0047/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0047/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-t0047/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-t0047/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0047/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-t0059/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-t0059/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0059/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..6ebc025ecec59a6c8be53072de153d6512107e42 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2011, + "reference_year": 2012 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..c5bf859307315b2ec7f7f3aa740e8bee53f56ccb --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2014,bread,final,69614,455.52 +2011,software,final,14753,885.99 +2012,vehicles,final,28446,61.82 +2011,machinery,final,29615,320.11 +2013,vehicles,final,26591,62.23 +2015,clothing,final,26820,178.74 +2015,machinery,final,27981,448.74 +2014,electricity to factories,intermediate,77457,559.08 +2014,software,final,15502,854.68 +2011,cotton yarn,intermediate,28958,824.08 +2012,software,final,14728,863.76 +2013,software,final,14607,848.93 +2014,cotton yarn,intermediate,30999,961.78 +2015,electricity to factories,intermediate,77757,581.34 +2012,electricity to factories,intermediate,73583,484.48 +2012,restaurant meals,final,55030,321.76 +2012,cotton yarn,intermediate,28896,863.55 +2013,bread,final,65859,432.07 +2013,clothing,final,25926,168.53 +2015,bread,final,68358,463.25 +2011,clothing,final,24361,174.25 +2012,flour,intermediate,50064,388.61 +2011,flour,intermediate,45340,391.12 +2011,restaurant meals,final,57427,306.44 +2014,restaurant meals,final,56365,377.08 +2012,clothing,final,24358,165.62 +2014,vehicles,final,24974,62.02 +2015,vehicles,final,24817,60.51 +2015,software,final,15405,870.18 +2014,flour,intermediate,58433,390.95 +2012,bread,final,65799,432.31 +2013,restaurant meals,final,55774,362.82 +2015,cotton yarn,intermediate,29756,949.51 +2013,electricity to factories,intermediate,76994,536.22 +2011,vehicles,final,29120,59.01 +2013,machinery,final,28704,398.59 +2013,flour,intermediate,54797,397.82 +2012,machinery,final,29384,356.01 +2011,electricity to factories,intermediate,73570,452.29 +2015,restaurant meals,final,58884,412.51 +2015,flour,intermediate,62054,401.68 +2013,cotton yarn,intermediate,29879,889.05 +2014,clothing,final,25522,170.48 +2014,machinery,final,29358,429.74 +2011,bread,final,64791,430.58 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..2a3477eea3df8cbc8368e3149ba346a610b41fab --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0059/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2012,4750 +2011,4703 +2013,4815 +2014,4895 +2015,4990 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0059/instruction.md b/tasks/price-index/price-index-national-accounts-d3-t0059/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cfd03eacb1455ed1a60e8409531ead53ddf7c901 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0059/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2011 and the reference year of the chain-linked index is 2012 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2012) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2012 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2011"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2011, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2012 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2012 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2011 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2011 to 2015, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-t0059/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-t0059/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0059/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-t0059/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-t0059/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0059/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-t0071/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-t0071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0071/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..4fbf189d332fb99b7f7062e0860dd9468fedb7cf --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2019, + "reference_year": 2016 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..da37964786432ea41707bc1a3400b38d56b03f8e --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2015,software,final,12466,513.44 +2019,flour,intermediate,26619,426.01 +2018,machinery,final,7276,587.77 +2018,restaurant meals,final,58786,720.36 +2018,housing services,final,26195,578.97 +2018,raw timber,intermediate,36797,868.44 +2015,housing services,final,26521,581.16 +2019,cotton yarn,intermediate,41937,438.48 +2015,machinery,final,6356,482.47 +2015,raw timber,intermediate,30257,852.21 +2017,restaurant meals,final,58054,707.21 +2016,software,final,13020,537.91 +2015,flour,intermediate,25763,337.97 +2018,bread,final,63426,414.14 +2017,housing services,final,25991,594.14 +2016,electricity to homes,final,70955,74.28 +2017,cotton yarn,intermediate,44367,430.32 +2016,flour,intermediate,25577,343.55 +2017,flour,intermediate,27791,368.26 +2019,electricity to homes,final,80999,93.15 +2017,software,final,12340,541.71 +2019,raw timber,intermediate,38112,923.01 +2015,electricity to homes,final,66663,66.42 +2016,cotton yarn,intermediate,45365,423.75 +2019,housing services,final,26985,558.80 +2015,restaurant meals,final,60386,747.03 +2017,electricity to homes,final,75052,81.13 +2019,machinery,final,7739,604.80 +2017,raw timber,intermediate,33933,855.43 +2019,software,final,11981,591.56 +2016,bread,final,66378,338.33 +2017,machinery,final,7006,540.60 +2019,bread,final,64232,437.08 +2017,bread,final,61536,377.18 +2015,bread,final,66682,302.90 +2018,electricity to homes,final,75789,90.00 +2018,flour,intermediate,27138,391.93 +2016,machinery,final,6644,490.76 +2016,restaurant meals,final,59759,728.06 +2018,software,final,12326,558.47 +2018,cotton yarn,intermediate,42699,444.77 +2019,restaurant meals,final,62151,715.54 +2016,raw timber,intermediate,30465,852.25 +2016,housing services,final,26448,589.64 +2015,cotton yarn,intermediate,48603,417.15 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..fa0bce3d7e2da0e33c736db04031d198268f93a1 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0071/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2016,16090 +2015,15995 +2019,16271 +2017,16111 +2018,16112 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0071/instruction.md b/tasks/price-index/price-index-national-accounts-d3-t0071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..047cdd7a0df3a3d877d2d1bcb840b3060aad8130 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0071/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2019 and the reference year of the chain-linked index is 2016 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2016) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2016 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2015"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2019, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2016 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2016 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2019 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2015 to 2019, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-t0071/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-t0071/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0071/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-t0071/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-t0071/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0071/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/price-index/price-index-national-accounts-d3-t0083/environment/Dockerfile b/tasks/price-index/price-index-national-accounts-d3-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0083/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/accounts.json b/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/accounts.json new file mode 100644 index 0000000000000000000000000000000000000000..f95e7bef0bc4214cce64da057a8fa8ee94fd0074 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/accounts.json @@ -0,0 +1,4 @@ +{ + "base_year": 2017, + "reference_year": 2019 +} diff --git a/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/output.csv b/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..34e60f442e12f24b1b6e81ed2b0b5db94f1c3739 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/output.csv @@ -0,0 +1,46 @@ +year,product,use,quantity,unit_price +2019,electricity to homes,final,89861,592.11 +2016,clothing,final,83144,41.71 +2020,raw timber,intermediate,69669,72.89 +2017,electricity to homes,final,83430,529.68 +2016,steel,intermediate,48051,778.11 +2020,electricity to homes,final,94849,604.89 +2020,clothing,final,81496,41.27 +2019,steel,intermediate,54435,840.28 +2016,software,final,75380,804.73 +2016,flour,intermediate,65071,728.45 +2017,health care,final,84809,780.36 +2019,flour,intermediate,68611,962.84 +2016,health care,final,84002,719.12 +2017,software,final,72915,786.67 +2018,clothing,final,82966,40.65 +2016,raw timber,intermediate,59089,60.75 +2018,restaurant meals,final,25613,736.53 +2020,housing services,final,33290,671.65 +2017,steel,intermediate,49081,802.02 +2016,restaurant meals,final,26558,649.27 +2020,health care,final,109381,974.50 +2019,restaurant meals,final,24355,762.01 +2018,steel,intermediate,50041,827.41 +2017,raw timber,intermediate,62749,62.69 +2018,housing services,final,35521,661.21 +2020,steel,intermediate,57323,822.04 +2018,health care,final,90616,867.73 +2018,software,final,73701,773.24 +2016,housing services,final,37908,626.84 +2019,raw timber,intermediate,67054,67.57 +2020,flour,intermediate,71277,1013.96 +2018,flour,intermediate,67205,921.92 +2019,clothing,final,79827,40.69 +2017,housing services,final,37109,638.37 +2018,electricity to homes,final,90011,577.94 +2019,software,final,76366,760.34 +2017,clothing,final,80529,41.13 +2020,restaurant meals,final,22610,834.56 +2016,electricity to homes,final,77968,480.72 +2019,housing services,final,36353,669.72 +2018,raw timber,intermediate,64429,64.03 +2017,restaurant meals,final,26774,676.46 +2017,flour,intermediate,65176,814.27 +2020,software,final,81125,767.52 +2019,health care,final,97988,909.50 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/population.csv b/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/population.csv new file mode 100644 index 0000000000000000000000000000000000000000..3d58733f5de5725d845e1484985fd16ecaa50db6 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0083/environment/workdir/population.csv @@ -0,0 +1,6 @@ +year,population +2020,3435 +2018,3399 +2016,3387 +2019,3415 +2017,3415 diff --git a/tasks/price-index/price-index-national-accounts-d3-t0083/instruction.md b/tasks/price-index/price-index-national-accounts-d3-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a99374f89bb60aab7c827902b5d6717afcd320e1 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0083/instruction.md @@ -0,0 +1,22 @@ +# National accounts: nominal, real and chain-linked GDP + +`output.csv` gives the quantity produced and the unit price of each product in a small economy over 5 years, in no particular order. GDP here is the value of **final** goods and services only: rows whose `use` is `intermediate` are inputs already contained in the value of the final products, so leave them out of every calculation. The base year for constant prices is 2017 and the reference year of the chain-linked index is 2019 (both also in `accounts.json`). + +The chain-linked volume index links each year to the year before at the earlier year's prices: + +- link(t) = sum(p_(t-1) x q_t) / sum(p_(t-1) x q_(t-1)) +- index(2019) = 100, and index(t) = index(t-1) x link(t) for each later year. For the years before 2019 work backwards: index(t-1) = index(t) / link(t). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: object keyed by year (as a string, for example `"2016"`). Each value has + - `nominal_gdp`: the year's output valued at the year's own prices, sum(p_t x q_t), 2 decimals. + - `real_gdp`: the year's output valued at the prices of the base year 2017, sum(p_base x q_t), 2 decimals. + - `deflator`: the GDP deflator, 100 x nominal GDP / real GDP, 2 decimals. + - `chain_index`: the chain-linked volume index, with 2019 = 100, 2 decimals. + - `chained_volume_gdp`: GDP in chained volume terms, nominal GDP of 2019 x chain index / 100, 2 decimals. + - `real_gdp_per_capita`: real GDP (at 2017 prices) divided by the year's population in `population.csv`, 2 decimals. +- `average_real_growth_percent`: the average annual growth rate of real GDP from 2016 to 2020, ((last / first)^(1/4) - 1) x 100, 2 decimals. +- `average_chain_growth_percent`: the same average annual growth rate computed from the chain-linked index, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/price-index/price-index-national-accounts-d3-t0083/solution/oracle.py b/tasks/price-index/price-index-national-accounts-d3-t0083/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baabac2d92c084bbf4c4e153e5ecfb353e00af --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0083/solution/oracle.py @@ -0,0 +1,82 @@ +"""Independent file-based solution; standard library only.""" +import csv, json, math +from pathlib import Path + +def rows(name): + with open(name) as f: return list(csv.DictReader(f)) +def load(name): return json.loads(Path(name).read_text()) +def median(x): + s=sorted(x); n=len(s) + return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2 + +def solve(): + if Path('basket.csv').exists(): + rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs} + keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years)) + rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {} + units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12} + p,q={},{} + for r in rs: + if r['item'] not in keep: continue + key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')] + p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity']) + base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100} + for y in years: + out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep) + if y==base: continue + l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep) + a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep) + fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]} + if 'pack_size' in rs[0]: + out['excluded_items']=sorted(names-set(keep)); out['fisher_change_percent']={b:100*(fish[b]/fish[a]-1) for a,b in zip(years,years[1:])} + return out + if Path('output.csv').exists(): + rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json') + years=sorted({r['year'] for r in rs}); base=str(cfg['base_year']); ps={(r['year'],r['product']):float(r['unit_price']) for r in rs} + nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years} + real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years} + out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}} + if 'reference_year' in cfg: + links={b:sum(ps[a,r['product']]*float(r['quantity']) for r in rs if r['year']==b)/nom[a] for a,b in zip(years,years[1:])} + cv={years[0]:100} + for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b] + factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()} + for y in years: out['years'][y]['chain_index']=cv[y] + if Path('population.csv').exists(): + pop={r['year']:int(r['population']) for r in rows('population.csv')} + for y in years: out['years'][y].update(chained_volume_gdp=nom[str(cfg['reference_year'])]*cv[y]/100,real_gdp_per_capita=real[y]/pop[y]) + for key,vals in [('average_real_growth_percent',real),('average_chain_growth_percent',cv)]: out[key]=100*((vals[years[-1]]/vals[years[0]])**(1/(len(years)-1))-1) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),chain_growth_percent=100*(cv[b]/cv[a]-1)) + else: + for a,b in zip(years,years[1:]): out['years'][b].update(real_growth_percent=100*(real[b]/real[a]-1),inflation_percent=100*(out['years'][b]['deflator']/out['years'][a]['deflator']-1)) + return out + if Path('households.csv').exists(): + rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[] + for r in rs: + inc=float(r['disposable_income']) if 'disposable_income' in r else sum(float(r[k]) for k in ['wages','self_employment_income','pensions_and_benefits'])-float(r['taxes_paid']) + if persons: + adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids + obs.extend([inc]*(adults+kids)); children.append((inc,kids)) + else: obs.append(inc) + obs.sort(); n=len(obs); total=sum(obs); k=n//5; shares=[100*sum(obs[j*k:(j+1)*k])/total for j in range(5)] + # Pairwise-distance Gini is independent of the generator's rank formula. + out={'persons' if persons else 'households':n,'mean_income':total/n,'median_income':median(obs),'gini':sum(abs(a-b) for a in obs for b in obs)/(2*n*total),'quintile_shares_percent':{'Q%d'%(j+1):v for j,v in enumerate(shares)},'s80_s20':shares[-1]/shares[0]} + if 'disposable_income' not in rs[0]: + line=.6*median(obs); poor=sum(x /logs/verifier/reward.txt diff --git a/tasks/price-index/price-index-national-accounts-d3-t0083/tests/verify.py b/tasks/price-index/price-index-national-accounts-d3-t0083/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/price-index/price-index-national-accounts-d3-t0083/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main()