birgermoell commited on
Commit
4cfad60
·
verified ·
1 Parent(s): 6190c97

Add 108 offline Harbor tasks for price-index

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/price-index/price-index-basket-indices-d1-e0000/environment/Dockerfile +3 -0
  2. tasks/price-index/price-index-basket-indices-d1-e0000/environment/workdir/basket.csv +16 -0
  3. tasks/price-index/price-index-basket-indices-d1-e0000/instruction.md +16 -0
  4. tasks/price-index/price-index-basket-indices-d1-e0000/solution/oracle.py +82 -0
  5. tasks/price-index/price-index-basket-indices-d1-e0000/solution/solve.sh +4 -0
  6. tasks/price-index/price-index-basket-indices-d1-e0000/task.toml +25 -0
  7. tasks/price-index/price-index-basket-indices-d1-e0000/tests/checks.json +65 -0
  8. tasks/price-index/price-index-basket-indices-d1-e0000/tests/test.sh +3 -0
  9. tasks/price-index/price-index-basket-indices-d1-e0000/tests/verify.py +116 -0
  10. tasks/price-index/price-index-basket-indices-d1-e0012/environment/Dockerfile +3 -0
  11. tasks/price-index/price-index-basket-indices-d1-e0012/environment/workdir/basket.csv +16 -0
  12. tasks/price-index/price-index-basket-indices-d1-e0012/instruction.md +16 -0
  13. tasks/price-index/price-index-basket-indices-d1-e0012/solution/oracle.py +82 -0
  14. tasks/price-index/price-index-basket-indices-d1-e0012/solution/solve.sh +4 -0
  15. tasks/price-index/price-index-basket-indices-d1-e0012/task.toml +25 -0
  16. tasks/price-index/price-index-basket-indices-d1-e0012/tests/checks.json +65 -0
  17. tasks/price-index/price-index-basket-indices-d1-e0012/tests/test.sh +3 -0
  18. tasks/price-index/price-index-basket-indices-d1-e0012/tests/verify.py +116 -0
  19. tasks/price-index/price-index-basket-indices-d1-t0000/environment/Dockerfile +3 -0
  20. tasks/price-index/price-index-basket-indices-d1-t0000/environment/workdir/basket.csv +16 -0
  21. tasks/price-index/price-index-basket-indices-d1-t0000/instruction.md +16 -0
  22. tasks/price-index/price-index-basket-indices-d1-t0000/solution/oracle.py +82 -0
  23. tasks/price-index/price-index-basket-indices-d1-t0000/solution/solve.sh +4 -0
  24. tasks/price-index/price-index-basket-indices-d1-t0000/task.toml +25 -0
  25. tasks/price-index/price-index-basket-indices-d1-t0000/tests/checks.json +65 -0
  26. tasks/price-index/price-index-basket-indices-d1-t0000/tests/test.sh +3 -0
  27. tasks/price-index/price-index-basket-indices-d1-t0000/tests/verify.py +116 -0
  28. tasks/price-index/price-index-basket-indices-d1-t0012/environment/Dockerfile +3 -0
  29. tasks/price-index/price-index-basket-indices-d1-t0012/environment/workdir/basket.csv +16 -0
  30. tasks/price-index/price-index-basket-indices-d1-t0012/instruction.md +16 -0
  31. tasks/price-index/price-index-basket-indices-d1-t0012/solution/oracle.py +82 -0
  32. tasks/price-index/price-index-basket-indices-d1-t0012/solution/solve.sh +4 -0
  33. tasks/price-index/price-index-basket-indices-d1-t0012/task.toml +25 -0
  34. tasks/price-index/price-index-basket-indices-d1-t0012/tests/checks.json +65 -0
  35. tasks/price-index/price-index-basket-indices-d1-t0012/tests/test.sh +3 -0
  36. tasks/price-index/price-index-basket-indices-d1-t0012/tests/verify.py +116 -0
  37. tasks/price-index/price-index-basket-indices-d1-t0024/environment/Dockerfile +3 -0
  38. tasks/price-index/price-index-basket-indices-d1-t0024/environment/workdir/basket.csv +16 -0
  39. tasks/price-index/price-index-basket-indices-d1-t0024/instruction.md +16 -0
  40. tasks/price-index/price-index-basket-indices-d1-t0024/solution/oracle.py +82 -0
  41. tasks/price-index/price-index-basket-indices-d1-t0024/solution/solve.sh +4 -0
  42. tasks/price-index/price-index-basket-indices-d1-t0024/task.toml +25 -0
  43. tasks/price-index/price-index-basket-indices-d1-t0024/tests/checks.json +65 -0
  44. tasks/price-index/price-index-basket-indices-d1-t0024/tests/test.sh +3 -0
  45. tasks/price-index/price-index-basket-indices-d1-t0024/tests/verify.py +116 -0
  46. tasks/price-index/price-index-basket-indices-d1-t0036/environment/Dockerfile +3 -0
  47. tasks/price-index/price-index-basket-indices-d1-t0036/environment/workdir/basket.csv +16 -0
  48. tasks/price-index/price-index-basket-indices-d1-t0036/instruction.md +16 -0
  49. tasks/price-index/price-index-basket-indices-d1-t0036/solution/oracle.py +82 -0
  50. tasks/price-index/price-index-basket-indices-d1-t0036/solution/solve.sh +4 -0
tasks/price-index/price-index-basket-indices-d1-e0000/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/price-index/price-index-basket-indices-d1-e0000/environment/workdir/basket.csv ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ item,period,price,quantity,unit
2
+ pasta,2016,1.48,191,kg
3
+ pasta,2017,1.48,191,kg
4
+ pasta,2018,1.55,194,kg
5
+ butter,2016,6.74,10,kg
6
+ butter,2017,6.58,10,kg
7
+ butter,2018,7.17,9,kg
8
+ tea,2016,16.04,160,kg
9
+ tea,2017,16.45,154,kg
10
+ tea,2018,18.25,150,kg
11
+ coffee,2016,12.20,13,kg
12
+ coffee,2017,11.73,14,kg
13
+ coffee,2018,12.51,14,kg
14
+ cheese,2016,11.41,138,kg
15
+ cheese,2017,12.13,134,kg
16
+ cheese,2018,11.75,128,kg
tasks/price-index/price-index-basket-indices-d1-e0000/instruction.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Price indices for a household basket
2
+
3
+ `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).
4
+
5
+ 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:
6
+
7
+ - Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0)
8
+ - Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t)
9
+ - Fisher index = square root of (Laspeyres x Paasche)
10
+
11
+ Write `answer.json` in this folder, a JSON object with:
12
+
13
+ - `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.
14
+ - `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals.
15
+
16
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/price-index/price-index-basket-indices-d1-e0000/solution/oracle.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent file-based solution; standard library only."""
2
+ import csv, json, math
3
+ from pathlib import Path
4
+
5
+ def rows(name):
6
+ with open(name) as f: return list(csv.DictReader(f))
7
+ def load(name): return json.loads(Path(name).read_text())
8
+ def median(x):
9
+ s=sorted(x); n=len(s)
10
+ return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2
11
+
12
+ def solve():
13
+ if Path('basket.csv').exists():
14
+ rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs}
15
+ keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years))
16
+ rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {}
17
+ units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12}
18
+ p,q={},{}
19
+ for r in rs:
20
+ if r['item'] not in keep: continue
21
+ key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')]
22
+ p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity'])
23
+ base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100}
24
+ for y in years:
25
+ out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep)
26
+ if y==base: continue
27
+ l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep)
28
+ a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep)
29
+ fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]}
30
+ if 'pack_size' in rs[0]:
31
+ 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:])}
32
+ return out
33
+ if Path('output.csv').exists():
34
+ rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json')
35
+ 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}
36
+ nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years}
37
+ real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years}
38
+ out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}}
39
+ if 'reference_year' in cfg:
40
+ 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:])}
41
+ cv={years[0]:100}
42
+ for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b]
43
+ factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()}
44
+ for y in years: out['years'][y]['chain_index']=cv[y]
45
+ if Path('population.csv').exists():
46
+ pop={r['year']:int(r['population']) for r in rows('population.csv')}
47
+ 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])
48
+ 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)
49
+ else:
50
+ 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))
51
+ else:
52
+ 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))
53
+ return out
54
+ if Path('households.csv').exists():
55
+ rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[]
56
+ for r in rs:
57
+ 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'])
58
+ if persons:
59
+ adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids
60
+ obs.extend([inc]*(adults+kids)); children.append((inc,kids))
61
+ else: obs.append(inc)
62
+ 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)]
63
+ # Pairwise-distance Gini is independent of the generator's rank formula.
64
+ 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]}
65
+ if 'disposable_income' not in rs[0]:
66
+ line=.6*median(obs); poor=sum(x<line for x in obs); unit='persons' if persons else 'households'
67
+ out.update(poverty_threshold=line,at_risk_of_poverty_rate_percent=100*poor/n); out[unit+'_at_risk']=poor
68
+ if persons:
69
+ pc=sum(k for x,k in children if x<line); out.update(children_at_risk=pc,child_at_risk_rate_percent=100*pc/sum(k for _,k in children))
70
+ return out
71
+ cfg=load('request.json'); wr=rows('weights.csv'); idx={(r['category'],r['month']):float(r['index']) for r in rows('indices.csv')}; a,b=cfg['comparison_month'],cfg['current_month']
72
+ w={r['category']:float(r['weight']) for r in wr}; cats=sorted(w)
73
+ def ix(c,m): return idx[c,m]*100/idx[c,cfg['weight_reference_month']] if 'weight_reference_month' in cfg else idx[c,m]
74
+ def aggregate(cs,m): return sum(w[c]*ix(c,m) for c in cs)/sum(w[c] for c in cs)
75
+ ia,ib=aggregate(cats,a),aggregate(cats,b); con={c:100*w[c]*(ix(c,b)-ix(c,a))/(sum(w.values())*ia) for c in cats}
76
+ out={'all_items_index':{a:ia,b:ib},'inflation_percent':100*(ib/ia-1),'contributions':con,'largest_contributor':max(cats,key=con.get),'smallest_contributor':min(cats,key=con.get)}
77
+ if 'special_group' in wr[0]:
78
+ groups={g:[r['category'] for r in wr if r['special_group']==g] for g in ['food','energy','other']}; core={m:aggregate(groups['other'],m) for m in [a,b]}
79
+ out.update(core_index=core,core_inflation_percent=100*(core[b]/core[a]-1),group_contributions={g:sum(con[c] for c in cs) for g,cs in groups.items()})
80
+ return out
81
+
82
+ if __name__=='__main__': Path('answer.json').write_text(json.dumps(solve()))
tasks/price-index/price-index-basket-indices-d1-e0000/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cd /app
4
+ python3 /solution/oracle.py
tasks/price-index/price-index-basket-indices-d1-e0000/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "price-index"
8
+ tags = ["price-index", "basket-indices", "isced-0311", "eval"]
9
+ isced_f = "0311"
10
+ family = "basket-indices"
11
+ split = "eval"
12
+ seed = 10000
13
+
14
+ [verifier]
15
+ timeout_sec = 120.0
16
+
17
+ [agent]
18
+ timeout_sec = 900.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 600.0
22
+ cpus = 1
23
+ memory_mb = 1024
24
+ storage_mb = 2048
25
+ allow_internet = false
tasks/price-index/price-index-basket-indices-d1-e0000/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "basket_cost.2016",
4
+ "type": "number",
5
+ "value": 4649.66,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "basket_cost.2017",
11
+ "type": "number",
12
+ "value": 4671.42,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "basket_cost.2018",
18
+ "type": "number",
19
+ "value": 4781.87,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "indices.2017.laspeyres",
25
+ "type": "number",
26
+ "value": 103.38,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "indices.2017.paasche",
32
+ "type": "number",
33
+ "value": 103.35,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "indices.2017.fisher",
39
+ "type": "number",
40
+ "value": 103.37,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "indices.2018.laspeyres",
46
+ "type": "number",
47
+ "value": 109.08,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "indices.2018.paasche",
53
+ "type": "number",
54
+ "value": 109.05,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "indices.2018.fisher",
60
+ "type": "number",
61
+ "value": 109.06,
62
+ "abs_tol": 0.01,
63
+ "weight": 1.0
64
+ }
65
+ ]
tasks/price-index/price-index-basket-indices-d1-e0000/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/price-index/price-index-basket-indices-d1-e0000/tests/verify.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Verifier for Renaissance Labs practice environments. Standard library only.
3
+
4
+ Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1].
5
+ The reward is the weighted share of checks that pass. A missing, unreadable or non-object
6
+ answer scores 0. Each check addresses one value in the answer by a dotted path.
7
+
8
+ Check types
9
+ int exact integer (a float with integral value is accepted; booleans are not)
10
+ number within abs_tol of value (default 1e-9); booleans and strings are rejected
11
+ str equal after trimming and case-folding
12
+ bool exact boolean
13
+ list ordered list; items compared as int/number/str according to "item" (default str)
14
+ set unordered collection of distinct strings (or ints)
15
+ custom a function in validators.py: name(answer, args) -> bool or float in [0, 1]
16
+ """
17
+ import argparse, json, math, os, sys
18
+
19
+ MISSING = object()
20
+
21
+ def lookup(obj, path):
22
+ cur = obj
23
+ for part in path.split("."):
24
+ if isinstance(cur, dict):
25
+ if part not in cur: return MISSING
26
+ cur = cur[part]
27
+ elif isinstance(cur, list):
28
+ try: cur = cur[int(part)]
29
+ except (ValueError, IndexError): return MISSING
30
+ else:
31
+ return MISSING
32
+ return cur
33
+
34
+ def is_num(x):
35
+ return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x)))
36
+
37
+ def eq_int(got, want):
38
+ return is_num(got) and float(got) == float(int(got)) and int(got) == want
39
+
40
+ def eq_num(got, want, tol):
41
+ return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12
42
+
43
+ def eq_str(got, want):
44
+ return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold()
45
+
46
+ def eq_item(got, want, kind, tol):
47
+ if kind == "int": return eq_int(got, want)
48
+ if kind == "number": return eq_num(got, want, tol)
49
+ return eq_str(got, want)
50
+
51
+ def run_check(answer, chk, validators):
52
+ t = chk["type"]
53
+ if t == "custom":
54
+ fn = getattr(validators, chk["name"], None) if validators else None
55
+ if fn is None: return 0.0
56
+ try: r = fn(answer, chk.get("args", {}))
57
+ except Exception: return 0.0
58
+ if r is True: return 1.0
59
+ if r is False or r is None: return 0.0
60
+ return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0
61
+ got = lookup(answer, chk["path"])
62
+ if got is MISSING: return 0.0
63
+ want, tol = chk["value"], chk.get("abs_tol", 1e-9)
64
+ if t == "int": ok = eq_int(got, want)
65
+ elif t == "number": ok = eq_num(got, want, tol)
66
+ elif t == "str": ok = eq_str(got, want)
67
+ elif t == "bool": ok = isinstance(got, bool) and got is want
68
+ elif t == "list":
69
+ 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))
70
+ elif t == "set":
71
+ kind = chk.get("item", "str")
72
+ if not isinstance(got, list): ok = False
73
+ else:
74
+ 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)
75
+ g = [norm(x) for x in got]; w = [norm(x) for x in want]
76
+ ok = None not in g and len(g) == len(set(g)) and set(g) == set(w)
77
+ else: ok = False
78
+ return 1.0 if ok else 0.0
79
+
80
+ def grade(answer, checks, validators=None):
81
+ """Return (reward, details). answer is the parsed JSON, or None if it could not be read."""
82
+ if not isinstance(answer, dict):
83
+ return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks]
84
+ total = sum(c.get("weight", 1.0) for c in checks)
85
+ got, details = 0.0, []
86
+ for c in checks:
87
+ s = run_check(answer, c, validators)
88
+ got += s * c.get("weight", 1.0)
89
+ details.append({"check": c.get("path", c.get("name")), "score": s})
90
+ return (round(got / total, 6) if total else 0.0), details
91
+
92
+ def main():
93
+ ap = argparse.ArgumentParser()
94
+ ap.add_argument("--answer", default="/app/answer.json")
95
+ ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json"))
96
+ ap.add_argument("--out", default="/logs/verifier")
97
+ a = ap.parse_args()
98
+ checks = json.load(open(a.checks))
99
+ try:
100
+ with open(a.answer) as f: answer = json.load(f)
101
+ except Exception:
102
+ answer = None
103
+ validators = None
104
+ here = os.path.dirname(os.path.abspath(__file__))
105
+ if os.path.exists(os.path.join(here, "validators.py")):
106
+ sys.path.insert(0, here)
107
+ import validators # noqa
108
+ reward, details = grade(answer, checks, validators)
109
+ os.makedirs(a.out, exist_ok=True)
110
+ with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward))
111
+ with open(os.path.join(a.out, "reward.json"), "w") as f:
112
+ json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f)
113
+ print("reward", reward)
114
+
115
+ if __name__ == "__main__":
116
+ main()
tasks/price-index/price-index-basket-indices-d1-e0012/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/price-index/price-index-basket-indices-d1-e0012/environment/workdir/basket.csv ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ item,period,price,quantity,unit
2
+ rice,2012,2.58,103,kg
3
+ rice,2013,2.51,101,kg
4
+ rice,2014,2.83,100,kg
5
+ potatoes,2012,1.68,99,kg
6
+ potatoes,2013,1.79,97,kg
7
+ potatoes,2014,1.75,100,kg
8
+ coffee,2012,13.50,186,kg
9
+ coffee,2013,14.03,170,kg
10
+ coffee,2014,15.32,161,kg
11
+ butter,2012,9.93,71,kg
12
+ butter,2013,9.87,75,kg
13
+ butter,2014,9.78,78,kg
14
+ eggs,2012,0.35,732,each
15
+ eggs,2013,0.36,727,each
16
+ eggs,2014,0.36,744,each
tasks/price-index/price-index-basket-indices-d1-e0012/instruction.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Price indices for a household basket
2
+
3
+ `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).
4
+
5
+ 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:
6
+
7
+ - Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0)
8
+ - Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t)
9
+ - Fisher index = square root of (Laspeyres x Paasche)
10
+
11
+ Write `answer.json` in this folder, a JSON object with:
12
+
13
+ - `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.
14
+ - `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals.
15
+
16
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/price-index/price-index-basket-indices-d1-e0012/solution/oracle.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent file-based solution; standard library only."""
2
+ import csv, json, math
3
+ from pathlib import Path
4
+
5
+ def rows(name):
6
+ with open(name) as f: return list(csv.DictReader(f))
7
+ def load(name): return json.loads(Path(name).read_text())
8
+ def median(x):
9
+ s=sorted(x); n=len(s)
10
+ return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2
11
+
12
+ def solve():
13
+ if Path('basket.csv').exists():
14
+ rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs}
15
+ keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years))
16
+ rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {}
17
+ units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12}
18
+ p,q={},{}
19
+ for r in rs:
20
+ if r['item'] not in keep: continue
21
+ key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')]
22
+ p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity'])
23
+ base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100}
24
+ for y in years:
25
+ out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep)
26
+ if y==base: continue
27
+ l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep)
28
+ a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep)
29
+ fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]}
30
+ if 'pack_size' in rs[0]:
31
+ 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:])}
32
+ return out
33
+ if Path('output.csv').exists():
34
+ rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json')
35
+ 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}
36
+ nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years}
37
+ real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years}
38
+ out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}}
39
+ if 'reference_year' in cfg:
40
+ 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:])}
41
+ cv={years[0]:100}
42
+ for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b]
43
+ factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()}
44
+ for y in years: out['years'][y]['chain_index']=cv[y]
45
+ if Path('population.csv').exists():
46
+ pop={r['year']:int(r['population']) for r in rows('population.csv')}
47
+ 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])
48
+ 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)
49
+ else:
50
+ 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))
51
+ else:
52
+ 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))
53
+ return out
54
+ if Path('households.csv').exists():
55
+ rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[]
56
+ for r in rs:
57
+ 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'])
58
+ if persons:
59
+ adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids
60
+ obs.extend([inc]*(adults+kids)); children.append((inc,kids))
61
+ else: obs.append(inc)
62
+ 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)]
63
+ # Pairwise-distance Gini is independent of the generator's rank formula.
64
+ 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]}
65
+ if 'disposable_income' not in rs[0]:
66
+ line=.6*median(obs); poor=sum(x<line for x in obs); unit='persons' if persons else 'households'
67
+ out.update(poverty_threshold=line,at_risk_of_poverty_rate_percent=100*poor/n); out[unit+'_at_risk']=poor
68
+ if persons:
69
+ pc=sum(k for x,k in children if x<line); out.update(children_at_risk=pc,child_at_risk_rate_percent=100*pc/sum(k for _,k in children))
70
+ return out
71
+ cfg=load('request.json'); wr=rows('weights.csv'); idx={(r['category'],r['month']):float(r['index']) for r in rows('indices.csv')}; a,b=cfg['comparison_month'],cfg['current_month']
72
+ w={r['category']:float(r['weight']) for r in wr}; cats=sorted(w)
73
+ def ix(c,m): return idx[c,m]*100/idx[c,cfg['weight_reference_month']] if 'weight_reference_month' in cfg else idx[c,m]
74
+ def aggregate(cs,m): return sum(w[c]*ix(c,m) for c in cs)/sum(w[c] for c in cs)
75
+ ia,ib=aggregate(cats,a),aggregate(cats,b); con={c:100*w[c]*(ix(c,b)-ix(c,a))/(sum(w.values())*ia) for c in cats}
76
+ out={'all_items_index':{a:ia,b:ib},'inflation_percent':100*(ib/ia-1),'contributions':con,'largest_contributor':max(cats,key=con.get),'smallest_contributor':min(cats,key=con.get)}
77
+ if 'special_group' in wr[0]:
78
+ groups={g:[r['category'] for r in wr if r['special_group']==g] for g in ['food','energy','other']}; core={m:aggregate(groups['other'],m) for m in [a,b]}
79
+ out.update(core_index=core,core_inflation_percent=100*(core[b]/core[a]-1),group_contributions={g:sum(con[c] for c in cs) for g,cs in groups.items()})
80
+ return out
81
+
82
+ if __name__=='__main__': Path('answer.json').write_text(json.dumps(solve()))
tasks/price-index/price-index-basket-indices-d1-e0012/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cd /app
4
+ python3 /solution/oracle.py
tasks/price-index/price-index-basket-indices-d1-e0012/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "price-index"
8
+ tags = ["price-index", "basket-indices", "isced-0311", "eval"]
9
+ isced_f = "0311"
10
+ family = "basket-indices"
11
+ split = "eval"
12
+ seed = 10012
13
+
14
+ [verifier]
15
+ timeout_sec = 120.0
16
+
17
+ [agent]
18
+ timeout_sec = 900.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 600.0
22
+ cpus = 1
23
+ memory_mb = 1024
24
+ storage_mb = 2048
25
+ allow_internet = false
tasks/price-index/price-index-basket-indices-d1-e0012/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "basket_cost.2012",
4
+ "type": "number",
5
+ "value": 3904.29,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "basket_cost.2013",
11
+ "type": "number",
12
+ "value": 3814.21,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "basket_cost.2014",
18
+ "type": "number",
19
+ "value": 3955.2,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "indices.2013.laspeyres",
25
+ "type": "number",
26
+ "value": 102.7,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "indices.2013.paasche",
32
+ "type": "number",
33
+ "value": 102.59,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "indices.2013.fisher",
39
+ "type": "number",
40
+ "value": 102.65,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "indices.2014.laspeyres",
46
+ "type": "number",
47
+ "value": 109.42,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "indices.2014.paasche",
53
+ "type": "number",
54
+ "value": 108.83,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "indices.2014.fisher",
60
+ "type": "number",
61
+ "value": 109.12,
62
+ "abs_tol": 0.01,
63
+ "weight": 1.0
64
+ }
65
+ ]
tasks/price-index/price-index-basket-indices-d1-e0012/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/price-index/price-index-basket-indices-d1-e0012/tests/verify.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Verifier for Renaissance Labs practice environments. Standard library only.
3
+
4
+ Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1].
5
+ The reward is the weighted share of checks that pass. A missing, unreadable or non-object
6
+ answer scores 0. Each check addresses one value in the answer by a dotted path.
7
+
8
+ Check types
9
+ int exact integer (a float with integral value is accepted; booleans are not)
10
+ number within abs_tol of value (default 1e-9); booleans and strings are rejected
11
+ str equal after trimming and case-folding
12
+ bool exact boolean
13
+ list ordered list; items compared as int/number/str according to "item" (default str)
14
+ set unordered collection of distinct strings (or ints)
15
+ custom a function in validators.py: name(answer, args) -> bool or float in [0, 1]
16
+ """
17
+ import argparse, json, math, os, sys
18
+
19
+ MISSING = object()
20
+
21
+ def lookup(obj, path):
22
+ cur = obj
23
+ for part in path.split("."):
24
+ if isinstance(cur, dict):
25
+ if part not in cur: return MISSING
26
+ cur = cur[part]
27
+ elif isinstance(cur, list):
28
+ try: cur = cur[int(part)]
29
+ except (ValueError, IndexError): return MISSING
30
+ else:
31
+ return MISSING
32
+ return cur
33
+
34
+ def is_num(x):
35
+ return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x)))
36
+
37
+ def eq_int(got, want):
38
+ return is_num(got) and float(got) == float(int(got)) and int(got) == want
39
+
40
+ def eq_num(got, want, tol):
41
+ return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12
42
+
43
+ def eq_str(got, want):
44
+ return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold()
45
+
46
+ def eq_item(got, want, kind, tol):
47
+ if kind == "int": return eq_int(got, want)
48
+ if kind == "number": return eq_num(got, want, tol)
49
+ return eq_str(got, want)
50
+
51
+ def run_check(answer, chk, validators):
52
+ t = chk["type"]
53
+ if t == "custom":
54
+ fn = getattr(validators, chk["name"], None) if validators else None
55
+ if fn is None: return 0.0
56
+ try: r = fn(answer, chk.get("args", {}))
57
+ except Exception: return 0.0
58
+ if r is True: return 1.0
59
+ if r is False or r is None: return 0.0
60
+ return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0
61
+ got = lookup(answer, chk["path"])
62
+ if got is MISSING: return 0.0
63
+ want, tol = chk["value"], chk.get("abs_tol", 1e-9)
64
+ if t == "int": ok = eq_int(got, want)
65
+ elif t == "number": ok = eq_num(got, want, tol)
66
+ elif t == "str": ok = eq_str(got, want)
67
+ elif t == "bool": ok = isinstance(got, bool) and got is want
68
+ elif t == "list":
69
+ 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))
70
+ elif t == "set":
71
+ kind = chk.get("item", "str")
72
+ if not isinstance(got, list): ok = False
73
+ else:
74
+ 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)
75
+ g = [norm(x) for x in got]; w = [norm(x) for x in want]
76
+ ok = None not in g and len(g) == len(set(g)) and set(g) == set(w)
77
+ else: ok = False
78
+ return 1.0 if ok else 0.0
79
+
80
+ def grade(answer, checks, validators=None):
81
+ """Return (reward, details). answer is the parsed JSON, or None if it could not be read."""
82
+ if not isinstance(answer, dict):
83
+ return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks]
84
+ total = sum(c.get("weight", 1.0) for c in checks)
85
+ got, details = 0.0, []
86
+ for c in checks:
87
+ s = run_check(answer, c, validators)
88
+ got += s * c.get("weight", 1.0)
89
+ details.append({"check": c.get("path", c.get("name")), "score": s})
90
+ return (round(got / total, 6) if total else 0.0), details
91
+
92
+ def main():
93
+ ap = argparse.ArgumentParser()
94
+ ap.add_argument("--answer", default="/app/answer.json")
95
+ ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json"))
96
+ ap.add_argument("--out", default="/logs/verifier")
97
+ a = ap.parse_args()
98
+ checks = json.load(open(a.checks))
99
+ try:
100
+ with open(a.answer) as f: answer = json.load(f)
101
+ except Exception:
102
+ answer = None
103
+ validators = None
104
+ here = os.path.dirname(os.path.abspath(__file__))
105
+ if os.path.exists(os.path.join(here, "validators.py")):
106
+ sys.path.insert(0, here)
107
+ import validators # noqa
108
+ reward, details = grade(answer, checks, validators)
109
+ os.makedirs(a.out, exist_ok=True)
110
+ with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward))
111
+ with open(os.path.join(a.out, "reward.json"), "w") as f:
112
+ json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f)
113
+ print("reward", reward)
114
+
115
+ if __name__ == "__main__":
116
+ main()
tasks/price-index/price-index-basket-indices-d1-t0000/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/price-index/price-index-basket-indices-d1-t0000/environment/workdir/basket.csv ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ item,period,price,quantity,unit
2
+ coffee,2010,9.04,166,kg
3
+ coffee,2011,9.89,165,kg
4
+ coffee,2012,10.91,165,kg
5
+ sugar,2010,1.42,18,kg
6
+ sugar,2011,1.52,17,kg
7
+ sugar,2012,1.65,17,kg
8
+ olive oil,2010,8.77,167,litre
9
+ olive oil,2011,9.65,165,litre
10
+ olive oil,2012,9.90,160,litre
11
+ pasta,2010,1.98,28,kg
12
+ pasta,2011,2.00,28,kg
13
+ pasta,2012,2.25,26,kg
14
+ bread,2010,2.45,34,kg
15
+ bread,2011,2.71,32,kg
16
+ bread,2012,2.94,32,kg
tasks/price-index/price-index-basket-indices-d1-t0000/instruction.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Price indices for a household basket
2
+
3
+ `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).
4
+
5
+ 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:
6
+
7
+ - Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0)
8
+ - Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t)
9
+ - Fisher index = square root of (Laspeyres x Paasche)
10
+
11
+ Write `answer.json` in this folder, a JSON object with:
12
+
13
+ - `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.
14
+ - `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals.
15
+
16
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/price-index/price-index-basket-indices-d1-t0000/solution/oracle.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent file-based solution; standard library only."""
2
+ import csv, json, math
3
+ from pathlib import Path
4
+
5
+ def rows(name):
6
+ with open(name) as f: return list(csv.DictReader(f))
7
+ def load(name): return json.loads(Path(name).read_text())
8
+ def median(x):
9
+ s=sorted(x); n=len(s)
10
+ return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2
11
+
12
+ def solve():
13
+ if Path('basket.csv').exists():
14
+ rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs}
15
+ keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years))
16
+ rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {}
17
+ units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12}
18
+ p,q={},{}
19
+ for r in rs:
20
+ if r['item'] not in keep: continue
21
+ key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')]
22
+ p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity'])
23
+ base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100}
24
+ for y in years:
25
+ out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep)
26
+ if y==base: continue
27
+ l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep)
28
+ a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep)
29
+ fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]}
30
+ if 'pack_size' in rs[0]:
31
+ 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:])}
32
+ return out
33
+ if Path('output.csv').exists():
34
+ rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json')
35
+ 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}
36
+ nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years}
37
+ real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years}
38
+ out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}}
39
+ if 'reference_year' in cfg:
40
+ 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:])}
41
+ cv={years[0]:100}
42
+ for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b]
43
+ factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()}
44
+ for y in years: out['years'][y]['chain_index']=cv[y]
45
+ if Path('population.csv').exists():
46
+ pop={r['year']:int(r['population']) for r in rows('population.csv')}
47
+ 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])
48
+ 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)
49
+ else:
50
+ 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))
51
+ else:
52
+ 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))
53
+ return out
54
+ if Path('households.csv').exists():
55
+ rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[]
56
+ for r in rs:
57
+ 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'])
58
+ if persons:
59
+ adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids
60
+ obs.extend([inc]*(adults+kids)); children.append((inc,kids))
61
+ else: obs.append(inc)
62
+ 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)]
63
+ # Pairwise-distance Gini is independent of the generator's rank formula.
64
+ 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]}
65
+ if 'disposable_income' not in rs[0]:
66
+ line=.6*median(obs); poor=sum(x<line for x in obs); unit='persons' if persons else 'households'
67
+ out.update(poverty_threshold=line,at_risk_of_poverty_rate_percent=100*poor/n); out[unit+'_at_risk']=poor
68
+ if persons:
69
+ pc=sum(k for x,k in children if x<line); out.update(children_at_risk=pc,child_at_risk_rate_percent=100*pc/sum(k for _,k in children))
70
+ return out
71
+ cfg=load('request.json'); wr=rows('weights.csv'); idx={(r['category'],r['month']):float(r['index']) for r in rows('indices.csv')}; a,b=cfg['comparison_month'],cfg['current_month']
72
+ w={r['category']:float(r['weight']) for r in wr}; cats=sorted(w)
73
+ def ix(c,m): return idx[c,m]*100/idx[c,cfg['weight_reference_month']] if 'weight_reference_month' in cfg else idx[c,m]
74
+ def aggregate(cs,m): return sum(w[c]*ix(c,m) for c in cs)/sum(w[c] for c in cs)
75
+ ia,ib=aggregate(cats,a),aggregate(cats,b); con={c:100*w[c]*(ix(c,b)-ix(c,a))/(sum(w.values())*ia) for c in cats}
76
+ out={'all_items_index':{a:ia,b:ib},'inflation_percent':100*(ib/ia-1),'contributions':con,'largest_contributor':max(cats,key=con.get),'smallest_contributor':min(cats,key=con.get)}
77
+ if 'special_group' in wr[0]:
78
+ groups={g:[r['category'] for r in wr if r['special_group']==g] for g in ['food','energy','other']}; core={m:aggregate(groups['other'],m) for m in [a,b]}
79
+ out.update(core_index=core,core_inflation_percent=100*(core[b]/core[a]-1),group_contributions={g:sum(con[c] for c in cs) for g,cs in groups.items()})
80
+ return out
81
+
82
+ if __name__=='__main__': Path('answer.json').write_text(json.dumps(solve()))
tasks/price-index/price-index-basket-indices-d1-t0000/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cd /app
4
+ python3 /solution/oracle.py
tasks/price-index/price-index-basket-indices-d1-t0000/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "price-index"
8
+ tags = ["price-index", "basket-indices", "isced-0311", "train"]
9
+ isced_f = "0311"
10
+ family = "basket-indices"
11
+ split = "train"
12
+ seed = 0
13
+
14
+ [verifier]
15
+ timeout_sec = 120.0
16
+
17
+ [agent]
18
+ timeout_sec = 900.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 600.0
22
+ cpus = 1
23
+ memory_mb = 1024
24
+ storage_mb = 2048
25
+ allow_internet = false
tasks/price-index/price-index-basket-indices-d1-t0000/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "basket_cost.2010",
4
+ "type": "number",
5
+ "value": 3129.53,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "basket_cost.2011",
11
+ "type": "number",
12
+ "value": 3392.66,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "basket_cost.2012",
18
+ "type": "number",
19
+ "value": 3564.78,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "indices.2011.laspeyres",
25
+ "type": "number",
26
+ "value": 109.56,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "indices.2011.paasche",
32
+ "type": "number",
33
+ "value": 109.56,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "indices.2011.fisher",
39
+ "type": "number",
40
+ "value": 109.56,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "indices.2012.laspeyres",
46
+ "type": "number",
47
+ "value": 116.86,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "indices.2012.paasche",
53
+ "type": "number",
54
+ "value": 116.92,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "indices.2012.fisher",
60
+ "type": "number",
61
+ "value": 116.89,
62
+ "abs_tol": 0.01,
63
+ "weight": 1.0
64
+ }
65
+ ]
tasks/price-index/price-index-basket-indices-d1-t0000/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/price-index/price-index-basket-indices-d1-t0000/tests/verify.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Verifier for Renaissance Labs practice environments. Standard library only.
3
+
4
+ Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1].
5
+ The reward is the weighted share of checks that pass. A missing, unreadable or non-object
6
+ answer scores 0. Each check addresses one value in the answer by a dotted path.
7
+
8
+ Check types
9
+ int exact integer (a float with integral value is accepted; booleans are not)
10
+ number within abs_tol of value (default 1e-9); booleans and strings are rejected
11
+ str equal after trimming and case-folding
12
+ bool exact boolean
13
+ list ordered list; items compared as int/number/str according to "item" (default str)
14
+ set unordered collection of distinct strings (or ints)
15
+ custom a function in validators.py: name(answer, args) -> bool or float in [0, 1]
16
+ """
17
+ import argparse, json, math, os, sys
18
+
19
+ MISSING = object()
20
+
21
+ def lookup(obj, path):
22
+ cur = obj
23
+ for part in path.split("."):
24
+ if isinstance(cur, dict):
25
+ if part not in cur: return MISSING
26
+ cur = cur[part]
27
+ elif isinstance(cur, list):
28
+ try: cur = cur[int(part)]
29
+ except (ValueError, IndexError): return MISSING
30
+ else:
31
+ return MISSING
32
+ return cur
33
+
34
+ def is_num(x):
35
+ return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x)))
36
+
37
+ def eq_int(got, want):
38
+ return is_num(got) and float(got) == float(int(got)) and int(got) == want
39
+
40
+ def eq_num(got, want, tol):
41
+ return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12
42
+
43
+ def eq_str(got, want):
44
+ return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold()
45
+
46
+ def eq_item(got, want, kind, tol):
47
+ if kind == "int": return eq_int(got, want)
48
+ if kind == "number": return eq_num(got, want, tol)
49
+ return eq_str(got, want)
50
+
51
+ def run_check(answer, chk, validators):
52
+ t = chk["type"]
53
+ if t == "custom":
54
+ fn = getattr(validators, chk["name"], None) if validators else None
55
+ if fn is None: return 0.0
56
+ try: r = fn(answer, chk.get("args", {}))
57
+ except Exception: return 0.0
58
+ if r is True: return 1.0
59
+ if r is False or r is None: return 0.0
60
+ return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0
61
+ got = lookup(answer, chk["path"])
62
+ if got is MISSING: return 0.0
63
+ want, tol = chk["value"], chk.get("abs_tol", 1e-9)
64
+ if t == "int": ok = eq_int(got, want)
65
+ elif t == "number": ok = eq_num(got, want, tol)
66
+ elif t == "str": ok = eq_str(got, want)
67
+ elif t == "bool": ok = isinstance(got, bool) and got is want
68
+ elif t == "list":
69
+ 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))
70
+ elif t == "set":
71
+ kind = chk.get("item", "str")
72
+ if not isinstance(got, list): ok = False
73
+ else:
74
+ 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)
75
+ g = [norm(x) for x in got]; w = [norm(x) for x in want]
76
+ ok = None not in g and len(g) == len(set(g)) and set(g) == set(w)
77
+ else: ok = False
78
+ return 1.0 if ok else 0.0
79
+
80
+ def grade(answer, checks, validators=None):
81
+ """Return (reward, details). answer is the parsed JSON, or None if it could not be read."""
82
+ if not isinstance(answer, dict):
83
+ return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks]
84
+ total = sum(c.get("weight", 1.0) for c in checks)
85
+ got, details = 0.0, []
86
+ for c in checks:
87
+ s = run_check(answer, c, validators)
88
+ got += s * c.get("weight", 1.0)
89
+ details.append({"check": c.get("path", c.get("name")), "score": s})
90
+ return (round(got / total, 6) if total else 0.0), details
91
+
92
+ def main():
93
+ ap = argparse.ArgumentParser()
94
+ ap.add_argument("--answer", default="/app/answer.json")
95
+ ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json"))
96
+ ap.add_argument("--out", default="/logs/verifier")
97
+ a = ap.parse_args()
98
+ checks = json.load(open(a.checks))
99
+ try:
100
+ with open(a.answer) as f: answer = json.load(f)
101
+ except Exception:
102
+ answer = None
103
+ validators = None
104
+ here = os.path.dirname(os.path.abspath(__file__))
105
+ if os.path.exists(os.path.join(here, "validators.py")):
106
+ sys.path.insert(0, here)
107
+ import validators # noqa
108
+ reward, details = grade(answer, checks, validators)
109
+ os.makedirs(a.out, exist_ok=True)
110
+ with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward))
111
+ with open(os.path.join(a.out, "reward.json"), "w") as f:
112
+ json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f)
113
+ print("reward", reward)
114
+
115
+ if __name__ == "__main__":
116
+ main()
tasks/price-index/price-index-basket-indices-d1-t0012/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/price-index/price-index-basket-indices-d1-t0012/environment/workdir/basket.csv ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ item,period,price,quantity,unit
2
+ tea,2019,15.11,80,kg
3
+ tea,2020,16.20,72,kg
4
+ tea,2021,16.19,67,kg
5
+ rice,2019,2.73,159,kg
6
+ rice,2020,2.63,154,kg
7
+ rice,2021,2.88,153,kg
8
+ cheese,2019,9.60,78,kg
9
+ cheese,2020,10.39,73,kg
10
+ cheese,2021,10.16,71,kg
11
+ butter,2019,10.09,175,kg
12
+ butter,2020,10.05,171,kg
13
+ butter,2021,10.12,163,kg
14
+ olive oil,2019,9.64,134,litre
15
+ olive oil,2020,9.32,140,litre
16
+ olive oil,2021,9.68,131,litre
tasks/price-index/price-index-basket-indices-d1-t0012/instruction.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Price indices for a household basket
2
+
3
+ `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).
4
+
5
+ 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:
6
+
7
+ - Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0)
8
+ - Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t)
9
+ - Fisher index = square root of (Laspeyres x Paasche)
10
+
11
+ Write `answer.json` in this folder, a JSON object with:
12
+
13
+ - `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.
14
+ - `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals.
15
+
16
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/price-index/price-index-basket-indices-d1-t0012/solution/oracle.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent file-based solution; standard library only."""
2
+ import csv, json, math
3
+ from pathlib import Path
4
+
5
+ def rows(name):
6
+ with open(name) as f: return list(csv.DictReader(f))
7
+ def load(name): return json.loads(Path(name).read_text())
8
+ def median(x):
9
+ s=sorted(x); n=len(s)
10
+ return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2
11
+
12
+ def solve():
13
+ if Path('basket.csv').exists():
14
+ rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs}
15
+ keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years))
16
+ rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {}
17
+ units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12}
18
+ p,q={},{}
19
+ for r in rs:
20
+ if r['item'] not in keep: continue
21
+ key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')]
22
+ p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity'])
23
+ base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100}
24
+ for y in years:
25
+ out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep)
26
+ if y==base: continue
27
+ l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep)
28
+ a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep)
29
+ fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]}
30
+ if 'pack_size' in rs[0]:
31
+ 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:])}
32
+ return out
33
+ if Path('output.csv').exists():
34
+ rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json')
35
+ 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}
36
+ nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years}
37
+ real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years}
38
+ out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}}
39
+ if 'reference_year' in cfg:
40
+ 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:])}
41
+ cv={years[0]:100}
42
+ for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b]
43
+ factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()}
44
+ for y in years: out['years'][y]['chain_index']=cv[y]
45
+ if Path('population.csv').exists():
46
+ pop={r['year']:int(r['population']) for r in rows('population.csv')}
47
+ 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])
48
+ 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)
49
+ else:
50
+ 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))
51
+ else:
52
+ 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))
53
+ return out
54
+ if Path('households.csv').exists():
55
+ rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[]
56
+ for r in rs:
57
+ 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'])
58
+ if persons:
59
+ adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids
60
+ obs.extend([inc]*(adults+kids)); children.append((inc,kids))
61
+ else: obs.append(inc)
62
+ 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)]
63
+ # Pairwise-distance Gini is independent of the generator's rank formula.
64
+ 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]}
65
+ if 'disposable_income' not in rs[0]:
66
+ line=.6*median(obs); poor=sum(x<line for x in obs); unit='persons' if persons else 'households'
67
+ out.update(poverty_threshold=line,at_risk_of_poverty_rate_percent=100*poor/n); out[unit+'_at_risk']=poor
68
+ if persons:
69
+ pc=sum(k for x,k in children if x<line); out.update(children_at_risk=pc,child_at_risk_rate_percent=100*pc/sum(k for _,k in children))
70
+ return out
71
+ cfg=load('request.json'); wr=rows('weights.csv'); idx={(r['category'],r['month']):float(r['index']) for r in rows('indices.csv')}; a,b=cfg['comparison_month'],cfg['current_month']
72
+ w={r['category']:float(r['weight']) for r in wr}; cats=sorted(w)
73
+ def ix(c,m): return idx[c,m]*100/idx[c,cfg['weight_reference_month']] if 'weight_reference_month' in cfg else idx[c,m]
74
+ def aggregate(cs,m): return sum(w[c]*ix(c,m) for c in cs)/sum(w[c] for c in cs)
75
+ ia,ib=aggregate(cats,a),aggregate(cats,b); con={c:100*w[c]*(ix(c,b)-ix(c,a))/(sum(w.values())*ia) for c in cats}
76
+ out={'all_items_index':{a:ia,b:ib},'inflation_percent':100*(ib/ia-1),'contributions':con,'largest_contributor':max(cats,key=con.get),'smallest_contributor':min(cats,key=con.get)}
77
+ if 'special_group' in wr[0]:
78
+ groups={g:[r['category'] for r in wr if r['special_group']==g] for g in ['food','energy','other']}; core={m:aggregate(groups['other'],m) for m in [a,b]}
79
+ out.update(core_index=core,core_inflation_percent=100*(core[b]/core[a]-1),group_contributions={g:sum(con[c] for c in cs) for g,cs in groups.items()})
80
+ return out
81
+
82
+ if __name__=='__main__': Path('answer.json').write_text(json.dumps(solve()))
tasks/price-index/price-index-basket-indices-d1-t0012/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cd /app
4
+ python3 /solution/oracle.py
tasks/price-index/price-index-basket-indices-d1-t0012/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "price-index"
8
+ tags = ["price-index", "basket-indices", "isced-0311", "train"]
9
+ isced_f = "0311"
10
+ family = "basket-indices"
11
+ split = "train"
12
+ seed = 12
13
+
14
+ [verifier]
15
+ timeout_sec = 120.0
16
+
17
+ [agent]
18
+ timeout_sec = 900.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 600.0
22
+ cpus = 1
23
+ memory_mb = 1024
24
+ storage_mb = 2048
25
+ allow_internet = false
tasks/price-index/price-index-basket-indices-d1-t0012/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "basket_cost.2019",
4
+ "type": "number",
5
+ "value": 5449.18,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "basket_cost.2020",
11
+ "type": "number",
12
+ "value": 5353.24,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "basket_cost.2021",
18
+ "type": "number",
19
+ "value": 5164.37,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "indices.2020.laspeyres",
25
+ "type": "number",
26
+ "value": 101.52,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "indices.2020.paasche",
32
+ "type": "number",
33
+ "value": 101.31,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "indices.2020.fisher",
39
+ "type": "number",
40
+ "value": 101.42,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "indices.2021.laspeyres",
46
+ "type": "number",
47
+ "value": 103.02,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "indices.2021.paasche",
53
+ "type": "number",
54
+ "value": 102.89,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "indices.2021.fisher",
60
+ "type": "number",
61
+ "value": 102.96,
62
+ "abs_tol": 0.01,
63
+ "weight": 1.0
64
+ }
65
+ ]
tasks/price-index/price-index-basket-indices-d1-t0012/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/price-index/price-index-basket-indices-d1-t0012/tests/verify.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Verifier for Renaissance Labs practice environments. Standard library only.
3
+
4
+ Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1].
5
+ The reward is the weighted share of checks that pass. A missing, unreadable or non-object
6
+ answer scores 0. Each check addresses one value in the answer by a dotted path.
7
+
8
+ Check types
9
+ int exact integer (a float with integral value is accepted; booleans are not)
10
+ number within abs_tol of value (default 1e-9); booleans and strings are rejected
11
+ str equal after trimming and case-folding
12
+ bool exact boolean
13
+ list ordered list; items compared as int/number/str according to "item" (default str)
14
+ set unordered collection of distinct strings (or ints)
15
+ custom a function in validators.py: name(answer, args) -> bool or float in [0, 1]
16
+ """
17
+ import argparse, json, math, os, sys
18
+
19
+ MISSING = object()
20
+
21
+ def lookup(obj, path):
22
+ cur = obj
23
+ for part in path.split("."):
24
+ if isinstance(cur, dict):
25
+ if part not in cur: return MISSING
26
+ cur = cur[part]
27
+ elif isinstance(cur, list):
28
+ try: cur = cur[int(part)]
29
+ except (ValueError, IndexError): return MISSING
30
+ else:
31
+ return MISSING
32
+ return cur
33
+
34
+ def is_num(x):
35
+ return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x)))
36
+
37
+ def eq_int(got, want):
38
+ return is_num(got) and float(got) == float(int(got)) and int(got) == want
39
+
40
+ def eq_num(got, want, tol):
41
+ return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12
42
+
43
+ def eq_str(got, want):
44
+ return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold()
45
+
46
+ def eq_item(got, want, kind, tol):
47
+ if kind == "int": return eq_int(got, want)
48
+ if kind == "number": return eq_num(got, want, tol)
49
+ return eq_str(got, want)
50
+
51
+ def run_check(answer, chk, validators):
52
+ t = chk["type"]
53
+ if t == "custom":
54
+ fn = getattr(validators, chk["name"], None) if validators else None
55
+ if fn is None: return 0.0
56
+ try: r = fn(answer, chk.get("args", {}))
57
+ except Exception: return 0.0
58
+ if r is True: return 1.0
59
+ if r is False or r is None: return 0.0
60
+ return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0
61
+ got = lookup(answer, chk["path"])
62
+ if got is MISSING: return 0.0
63
+ want, tol = chk["value"], chk.get("abs_tol", 1e-9)
64
+ if t == "int": ok = eq_int(got, want)
65
+ elif t == "number": ok = eq_num(got, want, tol)
66
+ elif t == "str": ok = eq_str(got, want)
67
+ elif t == "bool": ok = isinstance(got, bool) and got is want
68
+ elif t == "list":
69
+ 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))
70
+ elif t == "set":
71
+ kind = chk.get("item", "str")
72
+ if not isinstance(got, list): ok = False
73
+ else:
74
+ 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)
75
+ g = [norm(x) for x in got]; w = [norm(x) for x in want]
76
+ ok = None not in g and len(g) == len(set(g)) and set(g) == set(w)
77
+ else: ok = False
78
+ return 1.0 if ok else 0.0
79
+
80
+ def grade(answer, checks, validators=None):
81
+ """Return (reward, details). answer is the parsed JSON, or None if it could not be read."""
82
+ if not isinstance(answer, dict):
83
+ return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks]
84
+ total = sum(c.get("weight", 1.0) for c in checks)
85
+ got, details = 0.0, []
86
+ for c in checks:
87
+ s = run_check(answer, c, validators)
88
+ got += s * c.get("weight", 1.0)
89
+ details.append({"check": c.get("path", c.get("name")), "score": s})
90
+ return (round(got / total, 6) if total else 0.0), details
91
+
92
+ def main():
93
+ ap = argparse.ArgumentParser()
94
+ ap.add_argument("--answer", default="/app/answer.json")
95
+ ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json"))
96
+ ap.add_argument("--out", default="/logs/verifier")
97
+ a = ap.parse_args()
98
+ checks = json.load(open(a.checks))
99
+ try:
100
+ with open(a.answer) as f: answer = json.load(f)
101
+ except Exception:
102
+ answer = None
103
+ validators = None
104
+ here = os.path.dirname(os.path.abspath(__file__))
105
+ if os.path.exists(os.path.join(here, "validators.py")):
106
+ sys.path.insert(0, here)
107
+ import validators # noqa
108
+ reward, details = grade(answer, checks, validators)
109
+ os.makedirs(a.out, exist_ok=True)
110
+ with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward))
111
+ with open(os.path.join(a.out, "reward.json"), "w") as f:
112
+ json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f)
113
+ print("reward", reward)
114
+
115
+ if __name__ == "__main__":
116
+ main()
tasks/price-index/price-index-basket-indices-d1-t0024/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/price-index/price-index-basket-indices-d1-t0024/environment/workdir/basket.csv ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ item,period,price,quantity,unit
2
+ rice,2013,2.80,148,kg
3
+ rice,2014,3.15,129,kg
4
+ rice,2015,3.52,118,kg
5
+ chicken,2013,8.18,253,kg
6
+ chicken,2014,8.52,250,kg
7
+ chicken,2015,9.54,244,kg
8
+ yoghurt,2013,4.17,229,kg
9
+ yoghurt,2014,4.26,213,kg
10
+ yoghurt,2015,4.69,197,kg
11
+ pasta,2013,1.79,210,kg
12
+ pasta,2014,1.88,216,kg
13
+ pasta,2015,2.09,193,kg
14
+ milk,2013,0.97,62,litre
15
+ milk,2014,1.07,60,litre
16
+ milk,2015,1.14,59,litre
tasks/price-index/price-index-basket-indices-d1-t0024/instruction.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Price indices for a household basket
2
+
3
+ `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).
4
+
5
+ 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:
6
+
7
+ - Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0)
8
+ - Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t)
9
+ - Fisher index = square root of (Laspeyres x Paasche)
10
+
11
+ Write `answer.json` in this folder, a JSON object with:
12
+
13
+ - `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.
14
+ - `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals.
15
+
16
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/price-index/price-index-basket-indices-d1-t0024/solution/oracle.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent file-based solution; standard library only."""
2
+ import csv, json, math
3
+ from pathlib import Path
4
+
5
+ def rows(name):
6
+ with open(name) as f: return list(csv.DictReader(f))
7
+ def load(name): return json.loads(Path(name).read_text())
8
+ def median(x):
9
+ s=sorted(x); n=len(s)
10
+ return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2
11
+
12
+ def solve():
13
+ if Path('basket.csv').exists():
14
+ rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs}
15
+ keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years))
16
+ rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {}
17
+ units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12}
18
+ p,q={},{}
19
+ for r in rs:
20
+ if r['item'] not in keep: continue
21
+ key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')]
22
+ p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity'])
23
+ base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100}
24
+ for y in years:
25
+ out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep)
26
+ if y==base: continue
27
+ l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep)
28
+ a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep)
29
+ fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]}
30
+ if 'pack_size' in rs[0]:
31
+ 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:])}
32
+ return out
33
+ if Path('output.csv').exists():
34
+ rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json')
35
+ 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}
36
+ nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years}
37
+ real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years}
38
+ out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}}
39
+ if 'reference_year' in cfg:
40
+ 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:])}
41
+ cv={years[0]:100}
42
+ for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b]
43
+ factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()}
44
+ for y in years: out['years'][y]['chain_index']=cv[y]
45
+ if Path('population.csv').exists():
46
+ pop={r['year']:int(r['population']) for r in rows('population.csv')}
47
+ 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])
48
+ 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)
49
+ else:
50
+ 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))
51
+ else:
52
+ 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))
53
+ return out
54
+ if Path('households.csv').exists():
55
+ rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[]
56
+ for r in rs:
57
+ 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'])
58
+ if persons:
59
+ adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids
60
+ obs.extend([inc]*(adults+kids)); children.append((inc,kids))
61
+ else: obs.append(inc)
62
+ 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)]
63
+ # Pairwise-distance Gini is independent of the generator's rank formula.
64
+ 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]}
65
+ if 'disposable_income' not in rs[0]:
66
+ line=.6*median(obs); poor=sum(x<line for x in obs); unit='persons' if persons else 'households'
67
+ out.update(poverty_threshold=line,at_risk_of_poverty_rate_percent=100*poor/n); out[unit+'_at_risk']=poor
68
+ if persons:
69
+ pc=sum(k for x,k in children if x<line); out.update(children_at_risk=pc,child_at_risk_rate_percent=100*pc/sum(k for _,k in children))
70
+ return out
71
+ cfg=load('request.json'); wr=rows('weights.csv'); idx={(r['category'],r['month']):float(r['index']) for r in rows('indices.csv')}; a,b=cfg['comparison_month'],cfg['current_month']
72
+ w={r['category']:float(r['weight']) for r in wr}; cats=sorted(w)
73
+ def ix(c,m): return idx[c,m]*100/idx[c,cfg['weight_reference_month']] if 'weight_reference_month' in cfg else idx[c,m]
74
+ def aggregate(cs,m): return sum(w[c]*ix(c,m) for c in cs)/sum(w[c] for c in cs)
75
+ ia,ib=aggregate(cats,a),aggregate(cats,b); con={c:100*w[c]*(ix(c,b)-ix(c,a))/(sum(w.values())*ia) for c in cats}
76
+ out={'all_items_index':{a:ia,b:ib},'inflation_percent':100*(ib/ia-1),'contributions':con,'largest_contributor':max(cats,key=con.get),'smallest_contributor':min(cats,key=con.get)}
77
+ if 'special_group' in wr[0]:
78
+ groups={g:[r['category'] for r in wr if r['special_group']==g] for g in ['food','energy','other']}; core={m:aggregate(groups['other'],m) for m in [a,b]}
79
+ out.update(core_index=core,core_inflation_percent=100*(core[b]/core[a]-1),group_contributions={g:sum(con[c] for c in cs) for g,cs in groups.items()})
80
+ return out
81
+
82
+ if __name__=='__main__': Path('answer.json').write_text(json.dumps(solve()))
tasks/price-index/price-index-basket-indices-d1-t0024/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cd /app
4
+ python3 /solution/oracle.py
tasks/price-index/price-index-basket-indices-d1-t0024/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "price-index"
8
+ tags = ["price-index", "basket-indices", "isced-0311", "train"]
9
+ isced_f = "0311"
10
+ family = "basket-indices"
11
+ split = "train"
12
+ seed = 24
13
+
14
+ [verifier]
15
+ timeout_sec = 120.0
16
+
17
+ [agent]
18
+ timeout_sec = 900.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 600.0
22
+ cpus = 1
23
+ memory_mb = 1024
24
+ storage_mb = 2048
25
+ allow_internet = false
tasks/price-index/price-index-basket-indices-d1-t0024/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "basket_cost.2013",
4
+ "type": "number",
5
+ "value": 3874.91,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "basket_cost.2014",
11
+ "type": "number",
12
+ "value": 3914.01,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "basket_cost.2015",
18
+ "type": "number",
19
+ "value": 4137.68,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "indices.2014.laspeyres",
25
+ "type": "number",
26
+ "value": 104.74,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "indices.2014.paasche",
32
+ "type": "number",
33
+ "value": 104.67,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "indices.2014.fisher",
39
+ "type": "number",
40
+ "value": 104.71,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "indices.2015.laspeyres",
46
+ "type": "number",
47
+ "value": 116.6,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "indices.2015.paasche",
53
+ "type": "number",
54
+ "value": 116.54,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "indices.2015.fisher",
60
+ "type": "number",
61
+ "value": 116.57,
62
+ "abs_tol": 0.01,
63
+ "weight": 1.0
64
+ }
65
+ ]
tasks/price-index/price-index-basket-indices-d1-t0024/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/price-index/price-index-basket-indices-d1-t0024/tests/verify.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Verifier for Renaissance Labs practice environments. Standard library only.
3
+
4
+ Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1].
5
+ The reward is the weighted share of checks that pass. A missing, unreadable or non-object
6
+ answer scores 0. Each check addresses one value in the answer by a dotted path.
7
+
8
+ Check types
9
+ int exact integer (a float with integral value is accepted; booleans are not)
10
+ number within abs_tol of value (default 1e-9); booleans and strings are rejected
11
+ str equal after trimming and case-folding
12
+ bool exact boolean
13
+ list ordered list; items compared as int/number/str according to "item" (default str)
14
+ set unordered collection of distinct strings (or ints)
15
+ custom a function in validators.py: name(answer, args) -> bool or float in [0, 1]
16
+ """
17
+ import argparse, json, math, os, sys
18
+
19
+ MISSING = object()
20
+
21
+ def lookup(obj, path):
22
+ cur = obj
23
+ for part in path.split("."):
24
+ if isinstance(cur, dict):
25
+ if part not in cur: return MISSING
26
+ cur = cur[part]
27
+ elif isinstance(cur, list):
28
+ try: cur = cur[int(part)]
29
+ except (ValueError, IndexError): return MISSING
30
+ else:
31
+ return MISSING
32
+ return cur
33
+
34
+ def is_num(x):
35
+ return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x)))
36
+
37
+ def eq_int(got, want):
38
+ return is_num(got) and float(got) == float(int(got)) and int(got) == want
39
+
40
+ def eq_num(got, want, tol):
41
+ return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12
42
+
43
+ def eq_str(got, want):
44
+ return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold()
45
+
46
+ def eq_item(got, want, kind, tol):
47
+ if kind == "int": return eq_int(got, want)
48
+ if kind == "number": return eq_num(got, want, tol)
49
+ return eq_str(got, want)
50
+
51
+ def run_check(answer, chk, validators):
52
+ t = chk["type"]
53
+ if t == "custom":
54
+ fn = getattr(validators, chk["name"], None) if validators else None
55
+ if fn is None: return 0.0
56
+ try: r = fn(answer, chk.get("args", {}))
57
+ except Exception: return 0.0
58
+ if r is True: return 1.0
59
+ if r is False or r is None: return 0.0
60
+ return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0
61
+ got = lookup(answer, chk["path"])
62
+ if got is MISSING: return 0.0
63
+ want, tol = chk["value"], chk.get("abs_tol", 1e-9)
64
+ if t == "int": ok = eq_int(got, want)
65
+ elif t == "number": ok = eq_num(got, want, tol)
66
+ elif t == "str": ok = eq_str(got, want)
67
+ elif t == "bool": ok = isinstance(got, bool) and got is want
68
+ elif t == "list":
69
+ 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))
70
+ elif t == "set":
71
+ kind = chk.get("item", "str")
72
+ if not isinstance(got, list): ok = False
73
+ else:
74
+ 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)
75
+ g = [norm(x) for x in got]; w = [norm(x) for x in want]
76
+ ok = None not in g and len(g) == len(set(g)) and set(g) == set(w)
77
+ else: ok = False
78
+ return 1.0 if ok else 0.0
79
+
80
+ def grade(answer, checks, validators=None):
81
+ """Return (reward, details). answer is the parsed JSON, or None if it could not be read."""
82
+ if not isinstance(answer, dict):
83
+ return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks]
84
+ total = sum(c.get("weight", 1.0) for c in checks)
85
+ got, details = 0.0, []
86
+ for c in checks:
87
+ s = run_check(answer, c, validators)
88
+ got += s * c.get("weight", 1.0)
89
+ details.append({"check": c.get("path", c.get("name")), "score": s})
90
+ return (round(got / total, 6) if total else 0.0), details
91
+
92
+ def main():
93
+ ap = argparse.ArgumentParser()
94
+ ap.add_argument("--answer", default="/app/answer.json")
95
+ ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json"))
96
+ ap.add_argument("--out", default="/logs/verifier")
97
+ a = ap.parse_args()
98
+ checks = json.load(open(a.checks))
99
+ try:
100
+ with open(a.answer) as f: answer = json.load(f)
101
+ except Exception:
102
+ answer = None
103
+ validators = None
104
+ here = os.path.dirname(os.path.abspath(__file__))
105
+ if os.path.exists(os.path.join(here, "validators.py")):
106
+ sys.path.insert(0, here)
107
+ import validators # noqa
108
+ reward, details = grade(answer, checks, validators)
109
+ os.makedirs(a.out, exist_ok=True)
110
+ with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward))
111
+ with open(os.path.join(a.out, "reward.json"), "w") as f:
112
+ json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f)
113
+ print("reward", reward)
114
+
115
+ if __name__ == "__main__":
116
+ main()
tasks/price-index/price-index-basket-indices-d1-t0036/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/price-index/price-index-basket-indices-d1-t0036/environment/workdir/basket.csv ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ item,period,price,quantity,unit
2
+ bread,2016,2.64,189,kg
3
+ bread,2017,2.62,193,kg
4
+ bread,2018,2.68,195,kg
5
+ rice,2016,1.76,181,kg
6
+ rice,2017,1.99,166,kg
7
+ rice,2018,2.22,149,kg
8
+ sugar,2016,1.19,249,kg
9
+ sugar,2017,1.33,227,kg
10
+ sugar,2018,1.33,240,kg
11
+ apples,2016,2.38,223,kg
12
+ apples,2017,2.40,232,kg
13
+ apples,2018,2.34,242,kg
14
+ potatoes,2016,1.07,14,kg
15
+ potatoes,2017,1.18,13,kg
16
+ potatoes,2018,1.19,14,kg
tasks/price-index/price-index-basket-indices-d1-t0036/instruction.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Price indices for a household basket
2
+
3
+ `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).
4
+
5
+ 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:
6
+
7
+ - Laspeyres index = 100 x sum(p_t x q_0) / sum(p_0 x q_0)
8
+ - Paasche index = 100 x sum(p_t x q_t) / sum(p_0 x q_t)
9
+ - Fisher index = square root of (Laspeyres x Paasche)
10
+
11
+ Write `answer.json` in this folder, a JSON object with:
12
+
13
+ - `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.
14
+ - `indices`: object keyed by year, for every year after the base year. Each value has `laspeyres`, `paasche` and `fisher`, 2 decimals.
15
+
16
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/price-index/price-index-basket-indices-d1-t0036/solution/oracle.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent file-based solution; standard library only."""
2
+ import csv, json, math
3
+ from pathlib import Path
4
+
5
+ def rows(name):
6
+ with open(name) as f: return list(csv.DictReader(f))
7
+ def load(name): return json.loads(Path(name).read_text())
8
+ def median(x):
9
+ s=sorted(x); n=len(s)
10
+ return s[n//2] if n%2 else (s[n//2-1]+s[n//2])/2
11
+
12
+ def solve():
13
+ if Path('basket.csv').exists():
14
+ rs=rows('basket.csv'); years=sorted({r['period'] for r in rs}); names={r['item'] for r in rs}
15
+ keep=sorted(i for i in names if {r['period'] for r in rs if r['item']==i}==set(years))
16
+ rates={(r['currency'],r['period']):float(r['crn_per_unit']) for r in rows('exchange_rates.csv')} if Path('exchange_rates.csv').exists() else {}
17
+ units={'g':.001,'kg':1,'ml':.001,'cl':.01,'litre':1,'each':1,'dozen':12}
18
+ p,q={},{}
19
+ for r in rs:
20
+ if r['item'] not in keep: continue
21
+ key=(r['period'],r['item']); pack=float(r.get('pack_size',1))*units[r.get('pack_unit','each')]
22
+ p[key]=float(r['price'])*rates.get((r.get('currency','CRN'),r['period']),1)/pack; q[key]=float(r['quantity'])
23
+ base=years[0]; out={'basket_cost':{},'indices':{}}; fish={base:100}
24
+ for y in years:
25
+ out['basket_cost'][y]=sum(p[y,i]*q[y,i] for i in keep)
26
+ if y==base: continue
27
+ l=100*sum(p[y,i]*q[base,i] for i in keep)/sum(p[base,i]*q[base,i] for i in keep)
28
+ a=100*sum(p[y,i]*q[y,i] for i in keep)/sum(p[base,i]*q[y,i] for i in keep)
29
+ fish[y]=math.sqrt(l*a); out['indices'][y]={'laspeyres':l,'paasche':a,'fisher':fish[y]}
30
+ if 'pack_size' in rs[0]:
31
+ 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:])}
32
+ return out
33
+ if Path('output.csv').exists():
34
+ rs=[r for r in rows('output.csv') if r.get('use','final')=='final']; cfg=load('accounts.json')
35
+ 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}
36
+ nom={y:sum(float(r['unit_price'])*float(r['quantity']) for r in rs if r['year']==y) for y in years}
37
+ real={y:sum(ps[base,r['product']]*float(r['quantity']) for r in rs if r['year']==y) for y in years}
38
+ out={'years':{y:{'nominal_gdp':nom[y],'real_gdp':real[y],'deflator':100*nom[y]/real[y]} for y in years}}
39
+ if 'reference_year' in cfg:
40
+ 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:])}
41
+ cv={years[0]:100}
42
+ for a,b in zip(years,years[1:]): cv[b]=cv[a]*links[b]
43
+ factor=100/cv[str(cfg['reference_year'])]; cv={y:v*factor for y,v in cv.items()}
44
+ for y in years: out['years'][y]['chain_index']=cv[y]
45
+ if Path('population.csv').exists():
46
+ pop={r['year']:int(r['population']) for r in rows('population.csv')}
47
+ 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])
48
+ 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)
49
+ else:
50
+ 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))
51
+ else:
52
+ 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))
53
+ return out
54
+ if Path('households.csv').exists():
55
+ rs=rows('households.csv'); persons='members_14_or_over' in rs[0]; obs=[]; children=[]
56
+ for r in rs:
57
+ 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'])
58
+ if persons:
59
+ adults,kids=int(r['members_14_or_over']),int(r['children_under_14']); inc/=1+.5*(adults-1)+.3*kids
60
+ obs.extend([inc]*(adults+kids)); children.append((inc,kids))
61
+ else: obs.append(inc)
62
+ 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)]
63
+ # Pairwise-distance Gini is independent of the generator's rank formula.
64
+ 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]}
65
+ if 'disposable_income' not in rs[0]:
66
+ line=.6*median(obs); poor=sum(x<line for x in obs); unit='persons' if persons else 'households'
67
+ out.update(poverty_threshold=line,at_risk_of_poverty_rate_percent=100*poor/n); out[unit+'_at_risk']=poor
68
+ if persons:
69
+ pc=sum(k for x,k in children if x<line); out.update(children_at_risk=pc,child_at_risk_rate_percent=100*pc/sum(k for _,k in children))
70
+ return out
71
+ cfg=load('request.json'); wr=rows('weights.csv'); idx={(r['category'],r['month']):float(r['index']) for r in rows('indices.csv')}; a,b=cfg['comparison_month'],cfg['current_month']
72
+ w={r['category']:float(r['weight']) for r in wr}; cats=sorted(w)
73
+ def ix(c,m): return idx[c,m]*100/idx[c,cfg['weight_reference_month']] if 'weight_reference_month' in cfg else idx[c,m]
74
+ def aggregate(cs,m): return sum(w[c]*ix(c,m) for c in cs)/sum(w[c] for c in cs)
75
+ ia,ib=aggregate(cats,a),aggregate(cats,b); con={c:100*w[c]*(ix(c,b)-ix(c,a))/(sum(w.values())*ia) for c in cats}
76
+ out={'all_items_index':{a:ia,b:ib},'inflation_percent':100*(ib/ia-1),'contributions':con,'largest_contributor':max(cats,key=con.get),'smallest_contributor':min(cats,key=con.get)}
77
+ if 'special_group' in wr[0]:
78
+ groups={g:[r['category'] for r in wr if r['special_group']==g] for g in ['food','energy','other']}; core={m:aggregate(groups['other'],m) for m in [a,b]}
79
+ out.update(core_index=core,core_inflation_percent=100*(core[b]/core[a]-1),group_contributions={g:sum(con[c] for c in cs) for g,cs in groups.items()})
80
+ return out
81
+
82
+ if __name__=='__main__': Path('answer.json').write_text(json.dumps(solve()))
tasks/price-index/price-index-basket-indices-d1-t0036/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cd /app
4
+ python3 /solution/oracle.py