birgermoell commited on
Commit
06a1a13
·
verified ·
1 Parent(s): cf66d45

Add 108 offline Harbor tasks for emissions-inventory

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/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/Dockerfile +3 -0
  2. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/activity_data.csv +10 -0
  3. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/emission_factors.csv +11 -0
  4. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/inventory_boundary.md +5 -0
  5. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/unit_conversions.csv +9 -0
  6. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/instruction.md +20 -0
  7. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/oracle.py +138 -0
  8. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/solve.sh +4 -0
  9. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/task.toml +25 -0
  10. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/checks.json +65 -0
  11. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/test.sh +3 -0
  12. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/verify.py +116 -0
  13. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/Dockerfile +3 -0
  14. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/activity_data.csv +15 -0
  15. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/emission_factors.csv +11 -0
  16. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/inventory_boundary.md +5 -0
  17. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/unit_conversions.csv +9 -0
  18. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/instruction.md +20 -0
  19. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/oracle.py +138 -0
  20. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/solve.sh +4 -0
  21. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/task.toml +25 -0
  22. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/checks.json +65 -0
  23. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/test.sh +3 -0
  24. tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/verify.py +116 -0
  25. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/Dockerfile +3 -0
  26. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/activity_data.csv +10 -0
  27. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/emission_factors.csv +11 -0
  28. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/inventory_boundary.md +5 -0
  29. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/unit_conversions.csv +9 -0
  30. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/instruction.md +20 -0
  31. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/oracle.py +138 -0
  32. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/solve.sh +4 -0
  33. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/task.toml +25 -0
  34. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/checks.json +65 -0
  35. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/test.sh +3 -0
  36. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/verify.py +116 -0
  37. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/Dockerfile +3 -0
  38. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/activity_data.csv +10 -0
  39. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/emission_factors.csv +11 -0
  40. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/inventory_boundary.md +5 -0
  41. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/unit_conversions.csv +9 -0
  42. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/instruction.md +20 -0
  43. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/oracle.py +138 -0
  44. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/solve.sh +4 -0
  45. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/task.toml +25 -0
  46. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/checks.json +65 -0
  47. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/test.sh +3 -0
  48. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/verify.py +116 -0
  49. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/Dockerfile +3 -0
  50. tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/activity_data.csv +11 -0
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/activity_data.csv ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ record_id,site,invoice_date,source,quantity,unit,supplier_ref
2
+ R001,head_office,2019-03-25,purchased_electricity,194568,kWh,INV-88187
3
+ R002,head_office,2019-12-24,district_heating,158051,kWh,INV-83456
4
+ R003,head_office,2019-02-21,company_cars,147677,km,INV-42239
5
+ R004,head_office,2019-04-28,purchased_electricity,170868,kWh,INV-24442
6
+ R005,head_office,2019-12-06,rail_travel,3965,km,INV-68052
7
+ R006,head_office,2019-04-07,rail_travel,7235,km,INV-29827
8
+ R007,head_office,2019-09-14,purchased_electricity,159341,kWh,INV-44486
9
+ R008,head_office,2019-06-24,company_cars,123619,km,INV-34130
10
+ R009,head_office,2019-09-20,petrol_fleet,18651.1,litre,INV-13487
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/emission_factors.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ source,factor_kg_co2e_per_unit,unit,scope
2
+ business_flights,0.154,km,3
3
+ company_cars,0.179,km,1
4
+ diesel_fleet,2.41,litre,1
5
+ district_heating,0.0986,kWh,2
6
+ heating_oil,2.71,litre,1
7
+ natural_gas,0.182,kWh,1
8
+ petrol_fleet,2.53,litre,1
9
+ purchased_electricity,0.249,kWh,2
10
+ rail_travel,0.0362,km,3
11
+ waste_to_landfill,422.0,tonne,3
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/inventory_boundary.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Inventory boundary
2
+
3
+ - Organisation: Lindqvist Castings
4
+ - Reporting year: 2019 (calendar year, by invoice date)
5
+ - Reported: scopes 1, 2 and 3 in tonnes CO2e
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/unit_conversions.csv ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from_unit,to_unit,multiply_by,applies_to
2
+ MWh,kWh,1000,all
3
+ GJ,kWh,277.78,all
4
+ m3,kWh,10.59,natural_gas
5
+ m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100
6
+ mile,km,1.609344,all
7
+ kg,tonne,0.001,all
8
+ therm,kWh,29.3071,all
9
+ gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/instruction.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Emissions inventory: activity data
2
+
3
+ You are compiling the 2019 greenhouse-gas inventory for Lindqvist Castings (a synthetic organisation).
4
+
5
+ - `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used.
6
+ - `emission_factors.csv`: for each source, the emission factor in kg CO2e per unit, the unit it applies to, and the scope the source belongs to. Use these factors and this classification.
7
+ - `inventory_boundary.md`: the organisation and the reporting year.
8
+ - `unit_conversions.csv`: multiply a quantity in `from_unit` by `multiply_by` to get `to_unit`. A row applies to every source if `applies_to` is `all`, otherwise only to the sources listed there (separated by semicolons). Use these values.
9
+
10
+ Every record belongs to the 2019 reporting year.
11
+
12
+ For each record, convert the quantity to the unit of its source's emission factor if it is not already in that unit, multiply by the factor, and convert kg to tonnes (1 tonne = 1000 kg).
13
+
14
+ Write `answer.json` in this folder, a JSON object with:
15
+
16
+ - `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year.
17
+ - `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals.
18
+ - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals.
19
+
20
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/oracle.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reference solution for Emissions Inventory. Works only from the files in the current directory."""
3
+ import csv, json, os, re
4
+
5
+ def rows(name):
6
+ with open(name, newline="") as f: return list(csv.DictReader(f))
7
+
8
+ def text(name):
9
+ with open(name) as f: return f.read()
10
+
11
+ def activity():
12
+ year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1)
13
+ factors = dict((r["source"], r) for r in rows("emission_factors.csv"))
14
+ conv = rows("unit_conversions.csv")
15
+ recs = rows("activity_data.csv")
16
+ by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0
17
+ for r in recs:
18
+ if r["invoice_date"][:4] != year: continue
19
+ f = factors[r["source"]]
20
+ q = float(r["quantity"])
21
+ if r["unit"] != f["unit"]:
22
+ hit = [c for c in conv if c["from_unit"] == r["unit"] and c["to_unit"] == f["unit"] and (c["applies_to"] == "all" or r["source"] in c["applies_to"].split(";"))]
23
+ assert len(hit) == 1, (r, hit)
24
+ q *= float(hit[0]["multiply_by"])
25
+ e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0
26
+ by_source[r["source"]] = by_source.get(r["source"], 0.0) + e
27
+ if f["scope"] in ("1", "2", "3"):
28
+ by_scope["scope_" + f["scope"]] += e
29
+ by_site[r["site"]] = by_site.get(r["site"], 0.0) + e
30
+ else: outside += e
31
+ total = sum(by_scope.values())
32
+ in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")]
33
+ r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items())
34
+ return {"by_source": r2(by_source), "by_scope": r2(by_scope), "by_site": r2(by_site), "total_t_co2e": round(total, 2), "outside_scopes_t_co2e": round(outside, 2),
35
+ "scope_share_percent": dict((k, round(100 * v / total, 1)) for k, v in by_scope.items()), "largest_source": max(in_scope, key=lambda s: by_source[s])}
36
+
37
+ def multigas():
38
+ gwp = {}
39
+ for line in text("gwp_values.md").splitlines():
40
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
41
+ if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1])
42
+ factors = dict((r["category"], r) for r in rows("gas_factors.csv"))
43
+ to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001}
44
+ ans = {"sources": {}}
45
+ tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0}
46
+ full = {}
47
+ for r in rows("sources.csv"):
48
+ f = factors[r["category"]]
49
+ amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])])
50
+ co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0
51
+ ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0
52
+ n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0
53
+ e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0
54
+ ans["sources"][r["source_id"]] = {"co2_t": round(co2, 2), "ch4_kg": round(ch4, 2), "n2o_kg": round(n2o, 2), "co2e_t": round(e, 2)}
55
+ full[r["source_id"]] = e
56
+ tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0
57
+ hfc = 0.0
58
+ if os.path.exists("refrigerant_log.csv"):
59
+ for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0
60
+ grand = sum(tot.values()) + hfc
61
+ ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items())
62
+ ans["totals"]["co2e_t"] = round(grand, 2)
63
+ ans.update(refrigerants_t_co2e=round(hfc, 3), non_co2_share_percent=round(100 * (grand - tot["co2_t"]) / grand, 1), largest_source=max(full, key=lambda s: full[s]))
64
+ return ans
65
+
66
+ def series():
67
+ target = text("target.md")
68
+ base = int(re.search(r"Base year:\s*(\d{4})", target).group(1))
69
+ target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1))
70
+ cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1))
71
+ totals, output = {}, {}
72
+ if os.path.exists("annual_emissions.csv"):
73
+ for r in rows("annual_emissions.csv"):
74
+ totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"])
75
+ output[int(r["year"])] = float(r["output"])
76
+ else:
77
+ ledger, out = rows("emissions_ledger.csv"), rows("output.csv")
78
+ sold = re.search(r"Divested site:\s*(\w+)", target)
79
+ still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else [])
80
+ for r in ledger:
81
+ if r["site"] not in still: continue
82
+ y = int(r["year"])
83
+ totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0)
84
+ for r in out:
85
+ if "site" in r and r["site"] not in still: continue
86
+ output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"])
87
+ years = sorted(totals)
88
+ latest = years[-1]
89
+ ans = {"years": {}}
90
+ for i, y in enumerate(years):
91
+ o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)}
92
+ if y != base:
93
+ o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1)
94
+ o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1)
95
+ ans["years"][str(y)] = o
96
+ goal = totals[base] * (1 - cut / 100.0)
97
+ left = target_year - latest
98
+ path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base)
99
+ ans.update(target_t_co2e=round(goal, 1), required_annual_reduction_t=round((totals[latest] - goal) / left, 1), linear_path_latest_t=round(path, 1),
100
+ on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2))
101
+ return ans
102
+
103
+ def quality():
104
+ factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1))
105
+ seen, dups, site = {}, {}, {}
106
+ for r in rows("meter_readings.csv"):
107
+ m = r["meter_id"]
108
+ site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0)
109
+ kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0)
110
+ if r["month"] in seen[m]:
111
+ assert abs(seen[m][r["month"]] - kwh) < 1e-6
112
+ dups[m] += 1
113
+ else: seen[m][r["month"]] = kwh
114
+ year = sorted(next(iter(seen.values())))[0][:4]
115
+ months = ["%s-%02d" % (year, k) for k in range(1, 13)]
116
+ ans = {"meters": {}, "filled": {}, "meters_with_gap": []}
117
+ month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0
118
+ for m, have in seen.items():
119
+ filled = {}
120
+ for i, mo in enumerate(months):
121
+ if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0
122
+ if filled:
123
+ ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m)
124
+ have = dict(have); have.update(filled)
125
+ annual = sum(have.values())
126
+ ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]}
127
+ for mo in months: month_total[mo] += have[mo]
128
+ site_total[site[m]] = site_total.get(site[m], 0.0) + annual
129
+ total += annual
130
+ ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2),
131
+ by_site_t_co2e=dict((s, round(v * factor / 1000.0, 2)) for s, v in site_total.items()), peak_month=max(months, key=lambda mo: month_total[mo]))
132
+ return ans
133
+
134
+ if os.path.exists("activity_data.csv"): answer = activity()
135
+ elif os.path.exists("gwp_values.md"): answer = multigas()
136
+ elif os.path.exists("target.md"): answer = series()
137
+ else: answer = quality()
138
+ with open("answer.json", "w") as f: json.dump(answer, f, indent=1)
tasks/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-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 = "emissions-inventory"
8
+ tags = ["emissions-inventory", "activity-data", "isced-0521", "eval"]
9
+ isced_f = "0521"
10
+ family = "activity-data"
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/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "by_source.company_cars",
4
+ "type": "number",
5
+ "value": 48.56,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "by_source.district_heating",
11
+ "type": "number",
12
+ "value": 15.58,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "by_source.petrol_fleet",
18
+ "type": "number",
19
+ "value": 47.19,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "by_source.purchased_electricity",
25
+ "type": "number",
26
+ "value": 130.67,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "by_source.rail_travel",
32
+ "type": "number",
33
+ "value": 0.41,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "by_scope.scope_1",
39
+ "type": "number",
40
+ "value": 95.75,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "by_scope.scope_2",
46
+ "type": "number",
47
+ "value": 146.25,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "by_scope.scope_3",
53
+ "type": "number",
54
+ "value": 0.41,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "total_t_co2e",
60
+ "type": "number",
61
+ "value": 242.41,
62
+ "abs_tol": 0.01,
63
+ "weight": 2
64
+ }
65
+ ]
tasks/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/activity_data.csv ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ record_id,site,invoice_date,source,quantity,unit,supplier_ref
2
+ R001,head_office,2020-09-24,heating_oil,1866.0,litre,INV-61458
3
+ R002,head_office,2020-08-20,petrol_fleet,4018.3,litre,INV-32270
4
+ R003,head_office,2020-10-04,purchased_electricity,316661,kWh,INV-63632
5
+ R004,head_office,2020-06-20,heating_oil,2282.9,litre,INV-68354
6
+ R005,head_office,2020-12-05,heating_oil,3926.2,litre,INV-26480
7
+ R006,head_office,2020-04-21,purchased_electricity,215878,kWh,INV-12262
8
+ R007,head_office,2020-02-14,business_flights,22312,km,INV-11253
9
+ R008,head_office,2020-02-24,purchased_electricity,195090,kWh,INV-98331
10
+ R009,head_office,2020-04-16,petrol_fleet,3529.3,litre,INV-85057
11
+ R010,head_office,2020-10-26,company_cars,69310,mile,INV-31363
12
+ R011,head_office,2020-09-12,business_flights,7672,km,INV-54916
13
+ R012,head_office,2020-03-23,business_flights,15708,km,INV-58845
14
+ R013,head_office,2020-01-28,petrol_fleet,3363.4,litre,INV-80171
15
+ R014,head_office,2020-10-07,company_cars,106020,km,INV-38862
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/emission_factors.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ source,factor_kg_co2e_per_unit,unit,scope
2
+ business_flights,0.155,km,3
3
+ company_cars,0.183,km,1
4
+ diesel_fleet,2.91,litre,1
5
+ district_heating,0.0896,kWh,2
6
+ heating_oil,2.52,litre,1
7
+ natural_gas,0.174,kWh,1
8
+ petrol_fleet,2.49,litre,1
9
+ purchased_electricity,0.224,kWh,2
10
+ rail_travel,0.0317,km,3
11
+ waste_to_landfill,441.0,tonne,3
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/inventory_boundary.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Inventory boundary
2
+
3
+ - Organisation: Kestrel Joinery
4
+ - Reporting year: 2020 (calendar year, by invoice date)
5
+ - Reported: scopes 1, 2 and 3 in tonnes CO2e
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/unit_conversions.csv ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from_unit,to_unit,multiply_by,applies_to
2
+ MWh,kWh,1000,all
3
+ GJ,kWh,277.78,all
4
+ m3,kWh,10.84,natural_gas
5
+ m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100
6
+ mile,km,1.609344,all
7
+ kg,tonne,0.001,all
8
+ therm,kWh,29.3071,all
9
+ gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/instruction.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Emissions inventory: activity data
2
+
3
+ You are compiling the 2020 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation).
4
+
5
+ - `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used.
6
+ - `emission_factors.csv`: for each source, the emission factor in kg CO2e per unit, the unit it applies to, and the scope the source belongs to. Use these factors and this classification.
7
+ - `inventory_boundary.md`: the organisation and the reporting year.
8
+ - `unit_conversions.csv`: multiply a quantity in `from_unit` by `multiply_by` to get `to_unit`. A row applies to every source if `applies_to` is `all`, otherwise only to the sources listed there (separated by semicolons). Use these values.
9
+
10
+ Every record belongs to the 2020 reporting year.
11
+
12
+ For each record, convert the quantity to the unit of its source's emission factor if it is not already in that unit, multiply by the factor, and convert kg to tonnes (1 tonne = 1000 kg).
13
+
14
+ Write `answer.json` in this folder, a JSON object with:
15
+
16
+ - `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year.
17
+ - `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals.
18
+ - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals.
19
+
20
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/oracle.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reference solution for Emissions Inventory. Works only from the files in the current directory."""
3
+ import csv, json, os, re
4
+
5
+ def rows(name):
6
+ with open(name, newline="") as f: return list(csv.DictReader(f))
7
+
8
+ def text(name):
9
+ with open(name) as f: return f.read()
10
+
11
+ def activity():
12
+ year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1)
13
+ factors = dict((r["source"], r) for r in rows("emission_factors.csv"))
14
+ conv = rows("unit_conversions.csv")
15
+ recs = rows("activity_data.csv")
16
+ by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0
17
+ for r in recs:
18
+ if r["invoice_date"][:4] != year: continue
19
+ f = factors[r["source"]]
20
+ q = float(r["quantity"])
21
+ if r["unit"] != f["unit"]:
22
+ hit = [c for c in conv if c["from_unit"] == r["unit"] and c["to_unit"] == f["unit"] and (c["applies_to"] == "all" or r["source"] in c["applies_to"].split(";"))]
23
+ assert len(hit) == 1, (r, hit)
24
+ q *= float(hit[0]["multiply_by"])
25
+ e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0
26
+ by_source[r["source"]] = by_source.get(r["source"], 0.0) + e
27
+ if f["scope"] in ("1", "2", "3"):
28
+ by_scope["scope_" + f["scope"]] += e
29
+ by_site[r["site"]] = by_site.get(r["site"], 0.0) + e
30
+ else: outside += e
31
+ total = sum(by_scope.values())
32
+ in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")]
33
+ r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items())
34
+ return {"by_source": r2(by_source), "by_scope": r2(by_scope), "by_site": r2(by_site), "total_t_co2e": round(total, 2), "outside_scopes_t_co2e": round(outside, 2),
35
+ "scope_share_percent": dict((k, round(100 * v / total, 1)) for k, v in by_scope.items()), "largest_source": max(in_scope, key=lambda s: by_source[s])}
36
+
37
+ def multigas():
38
+ gwp = {}
39
+ for line in text("gwp_values.md").splitlines():
40
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
41
+ if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1])
42
+ factors = dict((r["category"], r) for r in rows("gas_factors.csv"))
43
+ to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001}
44
+ ans = {"sources": {}}
45
+ tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0}
46
+ full = {}
47
+ for r in rows("sources.csv"):
48
+ f = factors[r["category"]]
49
+ amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])])
50
+ co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0
51
+ ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0
52
+ n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0
53
+ e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0
54
+ ans["sources"][r["source_id"]] = {"co2_t": round(co2, 2), "ch4_kg": round(ch4, 2), "n2o_kg": round(n2o, 2), "co2e_t": round(e, 2)}
55
+ full[r["source_id"]] = e
56
+ tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0
57
+ hfc = 0.0
58
+ if os.path.exists("refrigerant_log.csv"):
59
+ for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0
60
+ grand = sum(tot.values()) + hfc
61
+ ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items())
62
+ ans["totals"]["co2e_t"] = round(grand, 2)
63
+ ans.update(refrigerants_t_co2e=round(hfc, 3), non_co2_share_percent=round(100 * (grand - tot["co2_t"]) / grand, 1), largest_source=max(full, key=lambda s: full[s]))
64
+ return ans
65
+
66
+ def series():
67
+ target = text("target.md")
68
+ base = int(re.search(r"Base year:\s*(\d{4})", target).group(1))
69
+ target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1))
70
+ cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1))
71
+ totals, output = {}, {}
72
+ if os.path.exists("annual_emissions.csv"):
73
+ for r in rows("annual_emissions.csv"):
74
+ totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"])
75
+ output[int(r["year"])] = float(r["output"])
76
+ else:
77
+ ledger, out = rows("emissions_ledger.csv"), rows("output.csv")
78
+ sold = re.search(r"Divested site:\s*(\w+)", target)
79
+ still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else [])
80
+ for r in ledger:
81
+ if r["site"] not in still: continue
82
+ y = int(r["year"])
83
+ totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0)
84
+ for r in out:
85
+ if "site" in r and r["site"] not in still: continue
86
+ output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"])
87
+ years = sorted(totals)
88
+ latest = years[-1]
89
+ ans = {"years": {}}
90
+ for i, y in enumerate(years):
91
+ o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)}
92
+ if y != base:
93
+ o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1)
94
+ o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1)
95
+ ans["years"][str(y)] = o
96
+ goal = totals[base] * (1 - cut / 100.0)
97
+ left = target_year - latest
98
+ path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base)
99
+ ans.update(target_t_co2e=round(goal, 1), required_annual_reduction_t=round((totals[latest] - goal) / left, 1), linear_path_latest_t=round(path, 1),
100
+ on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2))
101
+ return ans
102
+
103
+ def quality():
104
+ factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1))
105
+ seen, dups, site = {}, {}, {}
106
+ for r in rows("meter_readings.csv"):
107
+ m = r["meter_id"]
108
+ site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0)
109
+ kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0)
110
+ if r["month"] in seen[m]:
111
+ assert abs(seen[m][r["month"]] - kwh) < 1e-6
112
+ dups[m] += 1
113
+ else: seen[m][r["month"]] = kwh
114
+ year = sorted(next(iter(seen.values())))[0][:4]
115
+ months = ["%s-%02d" % (year, k) for k in range(1, 13)]
116
+ ans = {"meters": {}, "filled": {}, "meters_with_gap": []}
117
+ month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0
118
+ for m, have in seen.items():
119
+ filled = {}
120
+ for i, mo in enumerate(months):
121
+ if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0
122
+ if filled:
123
+ ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m)
124
+ have = dict(have); have.update(filled)
125
+ annual = sum(have.values())
126
+ ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]}
127
+ for mo in months: month_total[mo] += have[mo]
128
+ site_total[site[m]] = site_total.get(site[m], 0.0) + annual
129
+ total += annual
130
+ ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2),
131
+ by_site_t_co2e=dict((s, round(v * factor / 1000.0, 2)) for s, v in site_total.items()), peak_month=max(months, key=lambda mo: month_total[mo]))
132
+ return ans
133
+
134
+ if os.path.exists("activity_data.csv"): answer = activity()
135
+ elif os.path.exists("gwp_values.md"): answer = multigas()
136
+ elif os.path.exists("target.md"): answer = series()
137
+ else: answer = quality()
138
+ with open("answer.json", "w") as f: json.dump(answer, f, indent=1)
tasks/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-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 = "emissions-inventory"
8
+ tags = ["emissions-inventory", "activity-data", "isced-0521", "eval"]
9
+ isced_f = "0521"
10
+ family = "activity-data"
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/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "by_source.business_flights",
4
+ "type": "number",
5
+ "value": 7.08,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "by_source.company_cars",
11
+ "type": "number",
12
+ "value": 39.81,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "by_source.heating_oil",
18
+ "type": "number",
19
+ "value": 20.35,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "by_source.petrol_fleet",
25
+ "type": "number",
26
+ "value": 27.17,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "by_source.purchased_electricity",
32
+ "type": "number",
33
+ "value": 162.99,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "by_scope.scope_1",
39
+ "type": "number",
40
+ "value": 87.33,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "by_scope.scope_2",
46
+ "type": "number",
47
+ "value": 162.99,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "by_scope.scope_3",
53
+ "type": "number",
54
+ "value": 7.08,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "total_t_co2e",
60
+ "type": "number",
61
+ "value": 257.4,
62
+ "abs_tol": 0.01,
63
+ "weight": 2
64
+ }
65
+ ]
tasks/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/activity_data.csv ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ record_id,site,invoice_date,source,quantity,unit,supplier_ref
2
+ R001,head_office,2020-06-23,waste_to_landfill,26.71,tonne,INV-70192
3
+ R002,head_office,2020-08-20,waste_to_landfill,21442,kg,INV-78053
4
+ R003,head_office,2020-08-21,diesel_fleet,12465.6,litre,INV-34088
5
+ R004,head_office,2020-12-25,district_heating,487.353,MWh,INV-99329
6
+ R005,head_office,2020-02-24,rail_travel,174944,km,INV-74900
7
+ R006,head_office,2020-04-02,purchased_electricity,880.236,MWh,INV-61680
8
+ R007,head_office,2020-01-08,diesel_fleet,9336.4,litre,INV-28291
9
+ R008,head_office,2020-10-05,waste_to_landfill,15.14,tonne,INV-93432
10
+ R009,head_office,2020-02-06,diesel_fleet,8593.1,litre,INV-42114
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/emission_factors.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ source,factor_kg_co2e_per_unit,unit,scope
2
+ business_flights,0.165,km,3
3
+ company_cars,0.187,km,1
4
+ diesel_fleet,2.44,litre,1
5
+ district_heating,0.0915,kWh,2
6
+ heating_oil,2.32,litre,1
7
+ natural_gas,0.2,kWh,1
8
+ petrol_fleet,2.34,litre,1
9
+ purchased_electricity,0.231,kWh,2
10
+ rail_travel,0.0382,km,3
11
+ waste_to_landfill,484.0,tonne,3
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/inventory_boundary.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Inventory boundary
2
+
3
+ - Organisation: Ostervik Bakery Group
4
+ - Reporting year: 2020 (calendar year, by invoice date)
5
+ - Reported: scopes 1, 2 and 3 in tonnes CO2e
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/unit_conversions.csv ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from_unit,to_unit,multiply_by,applies_to
2
+ MWh,kWh,1000,all
3
+ GJ,kWh,277.78,all
4
+ m3,kWh,10.89,natural_gas
5
+ m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100
6
+ mile,km,1.609344,all
7
+ kg,tonne,0.001,all
8
+ therm,kWh,29.3071,all
9
+ gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/instruction.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Emissions inventory: activity data
2
+
3
+ You are compiling the 2020 greenhouse-gas inventory for Ostervik Bakery Group (a synthetic organisation).
4
+
5
+ - `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used.
6
+ - `emission_factors.csv`: for each source, the emission factor in kg CO2e per unit, the unit it applies to, and the scope the source belongs to. Use these factors and this classification.
7
+ - `inventory_boundary.md`: the organisation and the reporting year.
8
+ - `unit_conversions.csv`: multiply a quantity in `from_unit` by `multiply_by` to get `to_unit`. A row applies to every source if `applies_to` is `all`, otherwise only to the sources listed there (separated by semicolons). Use these values.
9
+
10
+ Every record belongs to the 2020 reporting year.
11
+
12
+ For each record, convert the quantity to the unit of its source's emission factor if it is not already in that unit, multiply by the factor, and convert kg to tonnes (1 tonne = 1000 kg).
13
+
14
+ Write `answer.json` in this folder, a JSON object with:
15
+
16
+ - `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year.
17
+ - `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals.
18
+ - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals.
19
+
20
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/oracle.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reference solution for Emissions Inventory. Works only from the files in the current directory."""
3
+ import csv, json, os, re
4
+
5
+ def rows(name):
6
+ with open(name, newline="") as f: return list(csv.DictReader(f))
7
+
8
+ def text(name):
9
+ with open(name) as f: return f.read()
10
+
11
+ def activity():
12
+ year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1)
13
+ factors = dict((r["source"], r) for r in rows("emission_factors.csv"))
14
+ conv = rows("unit_conversions.csv")
15
+ recs = rows("activity_data.csv")
16
+ by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0
17
+ for r in recs:
18
+ if r["invoice_date"][:4] != year: continue
19
+ f = factors[r["source"]]
20
+ q = float(r["quantity"])
21
+ if r["unit"] != f["unit"]:
22
+ hit = [c for c in conv if c["from_unit"] == r["unit"] and c["to_unit"] == f["unit"] and (c["applies_to"] == "all" or r["source"] in c["applies_to"].split(";"))]
23
+ assert len(hit) == 1, (r, hit)
24
+ q *= float(hit[0]["multiply_by"])
25
+ e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0
26
+ by_source[r["source"]] = by_source.get(r["source"], 0.0) + e
27
+ if f["scope"] in ("1", "2", "3"):
28
+ by_scope["scope_" + f["scope"]] += e
29
+ by_site[r["site"]] = by_site.get(r["site"], 0.0) + e
30
+ else: outside += e
31
+ total = sum(by_scope.values())
32
+ in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")]
33
+ r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items())
34
+ return {"by_source": r2(by_source), "by_scope": r2(by_scope), "by_site": r2(by_site), "total_t_co2e": round(total, 2), "outside_scopes_t_co2e": round(outside, 2),
35
+ "scope_share_percent": dict((k, round(100 * v / total, 1)) for k, v in by_scope.items()), "largest_source": max(in_scope, key=lambda s: by_source[s])}
36
+
37
+ def multigas():
38
+ gwp = {}
39
+ for line in text("gwp_values.md").splitlines():
40
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
41
+ if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1])
42
+ factors = dict((r["category"], r) for r in rows("gas_factors.csv"))
43
+ to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001}
44
+ ans = {"sources": {}}
45
+ tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0}
46
+ full = {}
47
+ for r in rows("sources.csv"):
48
+ f = factors[r["category"]]
49
+ amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])])
50
+ co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0
51
+ ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0
52
+ n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0
53
+ e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0
54
+ ans["sources"][r["source_id"]] = {"co2_t": round(co2, 2), "ch4_kg": round(ch4, 2), "n2o_kg": round(n2o, 2), "co2e_t": round(e, 2)}
55
+ full[r["source_id"]] = e
56
+ tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0
57
+ hfc = 0.0
58
+ if os.path.exists("refrigerant_log.csv"):
59
+ for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0
60
+ grand = sum(tot.values()) + hfc
61
+ ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items())
62
+ ans["totals"]["co2e_t"] = round(grand, 2)
63
+ ans.update(refrigerants_t_co2e=round(hfc, 3), non_co2_share_percent=round(100 * (grand - tot["co2_t"]) / grand, 1), largest_source=max(full, key=lambda s: full[s]))
64
+ return ans
65
+
66
+ def series():
67
+ target = text("target.md")
68
+ base = int(re.search(r"Base year:\s*(\d{4})", target).group(1))
69
+ target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1))
70
+ cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1))
71
+ totals, output = {}, {}
72
+ if os.path.exists("annual_emissions.csv"):
73
+ for r in rows("annual_emissions.csv"):
74
+ totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"])
75
+ output[int(r["year"])] = float(r["output"])
76
+ else:
77
+ ledger, out = rows("emissions_ledger.csv"), rows("output.csv")
78
+ sold = re.search(r"Divested site:\s*(\w+)", target)
79
+ still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else [])
80
+ for r in ledger:
81
+ if r["site"] not in still: continue
82
+ y = int(r["year"])
83
+ totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0)
84
+ for r in out:
85
+ if "site" in r and r["site"] not in still: continue
86
+ output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"])
87
+ years = sorted(totals)
88
+ latest = years[-1]
89
+ ans = {"years": {}}
90
+ for i, y in enumerate(years):
91
+ o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)}
92
+ if y != base:
93
+ o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1)
94
+ o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1)
95
+ ans["years"][str(y)] = o
96
+ goal = totals[base] * (1 - cut / 100.0)
97
+ left = target_year - latest
98
+ path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base)
99
+ ans.update(target_t_co2e=round(goal, 1), required_annual_reduction_t=round((totals[latest] - goal) / left, 1), linear_path_latest_t=round(path, 1),
100
+ on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2))
101
+ return ans
102
+
103
+ def quality():
104
+ factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1))
105
+ seen, dups, site = {}, {}, {}
106
+ for r in rows("meter_readings.csv"):
107
+ m = r["meter_id"]
108
+ site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0)
109
+ kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0)
110
+ if r["month"] in seen[m]:
111
+ assert abs(seen[m][r["month"]] - kwh) < 1e-6
112
+ dups[m] += 1
113
+ else: seen[m][r["month"]] = kwh
114
+ year = sorted(next(iter(seen.values())))[0][:4]
115
+ months = ["%s-%02d" % (year, k) for k in range(1, 13)]
116
+ ans = {"meters": {}, "filled": {}, "meters_with_gap": []}
117
+ month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0
118
+ for m, have in seen.items():
119
+ filled = {}
120
+ for i, mo in enumerate(months):
121
+ if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0
122
+ if filled:
123
+ ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m)
124
+ have = dict(have); have.update(filled)
125
+ annual = sum(have.values())
126
+ ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]}
127
+ for mo in months: month_total[mo] += have[mo]
128
+ site_total[site[m]] = site_total.get(site[m], 0.0) + annual
129
+ total += annual
130
+ ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2),
131
+ by_site_t_co2e=dict((s, round(v * factor / 1000.0, 2)) for s, v in site_total.items()), peak_month=max(months, key=lambda mo: month_total[mo]))
132
+ return ans
133
+
134
+ if os.path.exists("activity_data.csv"): answer = activity()
135
+ elif os.path.exists("gwp_values.md"): answer = multigas()
136
+ elif os.path.exists("target.md"): answer = series()
137
+ else: answer = quality()
138
+ with open("answer.json", "w") as f: json.dump(answer, f, indent=1)
tasks/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-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 = "emissions-inventory"
8
+ tags = ["emissions-inventory", "activity-data", "isced-0521", "train"]
9
+ isced_f = "0521"
10
+ family = "activity-data"
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/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "by_source.diesel_fleet",
4
+ "type": "number",
5
+ "value": 74.16,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "by_source.district_heating",
11
+ "type": "number",
12
+ "value": 44.59,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "by_source.purchased_electricity",
18
+ "type": "number",
19
+ "value": 203.33,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "by_source.rail_travel",
25
+ "type": "number",
26
+ "value": 6.68,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "by_source.waste_to_landfill",
32
+ "type": "number",
33
+ "value": 30.63,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "by_scope.scope_1",
39
+ "type": "number",
40
+ "value": 74.16,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "by_scope.scope_2",
46
+ "type": "number",
47
+ "value": 247.93,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "by_scope.scope_3",
53
+ "type": "number",
54
+ "value": 37.32,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "total_t_co2e",
60
+ "type": "number",
61
+ "value": 359.41,
62
+ "abs_tol": 0.01,
63
+ "weight": 2
64
+ }
65
+ ]
tasks/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/activity_data.csv ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ record_id,site,invoice_date,source,quantity,unit,supplier_ref
2
+ R001,head_office,2023-08-28,waste_to_landfill,20.06,tonne,INV-99397
3
+ R002,head_office,2023-11-20,petrol_fleet,3188.3,litre,INV-49218
4
+ R003,head_office,2023-08-14,diesel_fleet,29926.2,litre,INV-75638
5
+ R004,head_office,2023-09-27,purchased_electricity,666822,kWh,INV-94147
6
+ R005,head_office,2023-12-08,business_flights,58680,km,INV-54911
7
+ R006,head_office,2023-11-08,petrol_fleet,2565.9,litre,INV-85580
8
+ R007,head_office,2023-02-11,waste_to_landfill,26.07,tonne,INV-96796
9
+ R008,head_office,2023-10-18,business_flights,28964,km,INV-91899
10
+ R009,head_office,2023-07-25,waste_to_landfill,32075,kg,INV-95031
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/emission_factors.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ source,factor_kg_co2e_per_unit,unit,scope
2
+ business_flights,0.168,km,3
3
+ company_cars,0.178,km,1
4
+ diesel_fleet,2.85,litre,1
5
+ district_heating,0.092,kWh,2
6
+ heating_oil,2.4,litre,1
7
+ natural_gas,0.178,kWh,1
8
+ petrol_fleet,2.41,litre,1
9
+ purchased_electricity,0.226,kWh,2
10
+ rail_travel,0.0343,km,3
11
+ waste_to_landfill,410.0,tonne,3
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/inventory_boundary.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Inventory boundary
2
+
3
+ - Organisation: Ostervik Bakery Group
4
+ - Reporting year: 2023 (calendar year, by invoice date)
5
+ - Reported: scopes 1, 2 and 3 in tonnes CO2e
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/unit_conversions.csv ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from_unit,to_unit,multiply_by,applies_to
2
+ MWh,kWh,1000,all
3
+ GJ,kWh,277.78,all
4
+ m3,kWh,10.98,natural_gas
5
+ m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100
6
+ mile,km,1.609344,all
7
+ kg,tonne,0.001,all
8
+ therm,kWh,29.3071,all
9
+ gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/instruction.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Emissions inventory: activity data
2
+
3
+ You are compiling the 2023 greenhouse-gas inventory for Ostervik Bakery Group (a synthetic organisation).
4
+
5
+ - `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used.
6
+ - `emission_factors.csv`: for each source, the emission factor in kg CO2e per unit, the unit it applies to, and the scope the source belongs to. Use these factors and this classification.
7
+ - `inventory_boundary.md`: the organisation and the reporting year.
8
+ - `unit_conversions.csv`: multiply a quantity in `from_unit` by `multiply_by` to get `to_unit`. A row applies to every source if `applies_to` is `all`, otherwise only to the sources listed there (separated by semicolons). Use these values.
9
+
10
+ Every record belongs to the 2023 reporting year.
11
+
12
+ For each record, convert the quantity to the unit of its source's emission factor if it is not already in that unit, multiply by the factor, and convert kg to tonnes (1 tonne = 1000 kg).
13
+
14
+ Write `answer.json` in this folder, a JSON object with:
15
+
16
+ - `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year.
17
+ - `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals.
18
+ - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals.
19
+
20
+ Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for.
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/oracle.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reference solution for Emissions Inventory. Works only from the files in the current directory."""
3
+ import csv, json, os, re
4
+
5
+ def rows(name):
6
+ with open(name, newline="") as f: return list(csv.DictReader(f))
7
+
8
+ def text(name):
9
+ with open(name) as f: return f.read()
10
+
11
+ def activity():
12
+ year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1)
13
+ factors = dict((r["source"], r) for r in rows("emission_factors.csv"))
14
+ conv = rows("unit_conversions.csv")
15
+ recs = rows("activity_data.csv")
16
+ by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0
17
+ for r in recs:
18
+ if r["invoice_date"][:4] != year: continue
19
+ f = factors[r["source"]]
20
+ q = float(r["quantity"])
21
+ if r["unit"] != f["unit"]:
22
+ hit = [c for c in conv if c["from_unit"] == r["unit"] and c["to_unit"] == f["unit"] and (c["applies_to"] == "all" or r["source"] in c["applies_to"].split(";"))]
23
+ assert len(hit) == 1, (r, hit)
24
+ q *= float(hit[0]["multiply_by"])
25
+ e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0
26
+ by_source[r["source"]] = by_source.get(r["source"], 0.0) + e
27
+ if f["scope"] in ("1", "2", "3"):
28
+ by_scope["scope_" + f["scope"]] += e
29
+ by_site[r["site"]] = by_site.get(r["site"], 0.0) + e
30
+ else: outside += e
31
+ total = sum(by_scope.values())
32
+ in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")]
33
+ r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items())
34
+ return {"by_source": r2(by_source), "by_scope": r2(by_scope), "by_site": r2(by_site), "total_t_co2e": round(total, 2), "outside_scopes_t_co2e": round(outside, 2),
35
+ "scope_share_percent": dict((k, round(100 * v / total, 1)) for k, v in by_scope.items()), "largest_source": max(in_scope, key=lambda s: by_source[s])}
36
+
37
+ def multigas():
38
+ gwp = {}
39
+ for line in text("gwp_values.md").splitlines():
40
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
41
+ if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1])
42
+ factors = dict((r["category"], r) for r in rows("gas_factors.csv"))
43
+ to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001}
44
+ ans = {"sources": {}}
45
+ tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0}
46
+ full = {}
47
+ for r in rows("sources.csv"):
48
+ f = factors[r["category"]]
49
+ amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])])
50
+ co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0
51
+ ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0
52
+ n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0
53
+ e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0
54
+ ans["sources"][r["source_id"]] = {"co2_t": round(co2, 2), "ch4_kg": round(ch4, 2), "n2o_kg": round(n2o, 2), "co2e_t": round(e, 2)}
55
+ full[r["source_id"]] = e
56
+ tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0
57
+ hfc = 0.0
58
+ if os.path.exists("refrigerant_log.csv"):
59
+ for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0
60
+ grand = sum(tot.values()) + hfc
61
+ ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items())
62
+ ans["totals"]["co2e_t"] = round(grand, 2)
63
+ ans.update(refrigerants_t_co2e=round(hfc, 3), non_co2_share_percent=round(100 * (grand - tot["co2_t"]) / grand, 1), largest_source=max(full, key=lambda s: full[s]))
64
+ return ans
65
+
66
+ def series():
67
+ target = text("target.md")
68
+ base = int(re.search(r"Base year:\s*(\d{4})", target).group(1))
69
+ target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1))
70
+ cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1))
71
+ totals, output = {}, {}
72
+ if os.path.exists("annual_emissions.csv"):
73
+ for r in rows("annual_emissions.csv"):
74
+ totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"])
75
+ output[int(r["year"])] = float(r["output"])
76
+ else:
77
+ ledger, out = rows("emissions_ledger.csv"), rows("output.csv")
78
+ sold = re.search(r"Divested site:\s*(\w+)", target)
79
+ still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else [])
80
+ for r in ledger:
81
+ if r["site"] not in still: continue
82
+ y = int(r["year"])
83
+ totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0)
84
+ for r in out:
85
+ if "site" in r and r["site"] not in still: continue
86
+ output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"])
87
+ years = sorted(totals)
88
+ latest = years[-1]
89
+ ans = {"years": {}}
90
+ for i, y in enumerate(years):
91
+ o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)}
92
+ if y != base:
93
+ o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1)
94
+ o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1)
95
+ ans["years"][str(y)] = o
96
+ goal = totals[base] * (1 - cut / 100.0)
97
+ left = target_year - latest
98
+ path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base)
99
+ ans.update(target_t_co2e=round(goal, 1), required_annual_reduction_t=round((totals[latest] - goal) / left, 1), linear_path_latest_t=round(path, 1),
100
+ on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2))
101
+ return ans
102
+
103
+ def quality():
104
+ factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1))
105
+ seen, dups, site = {}, {}, {}
106
+ for r in rows("meter_readings.csv"):
107
+ m = r["meter_id"]
108
+ site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0)
109
+ kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0)
110
+ if r["month"] in seen[m]:
111
+ assert abs(seen[m][r["month"]] - kwh) < 1e-6
112
+ dups[m] += 1
113
+ else: seen[m][r["month"]] = kwh
114
+ year = sorted(next(iter(seen.values())))[0][:4]
115
+ months = ["%s-%02d" % (year, k) for k in range(1, 13)]
116
+ ans = {"meters": {}, "filled": {}, "meters_with_gap": []}
117
+ month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0
118
+ for m, have in seen.items():
119
+ filled = {}
120
+ for i, mo in enumerate(months):
121
+ if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0
122
+ if filled:
123
+ ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m)
124
+ have = dict(have); have.update(filled)
125
+ annual = sum(have.values())
126
+ ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]}
127
+ for mo in months: month_total[mo] += have[mo]
128
+ site_total[site[m]] = site_total.get(site[m], 0.0) + annual
129
+ total += annual
130
+ ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2),
131
+ by_site_t_co2e=dict((s, round(v * factor / 1000.0, 2)) for s, v in site_total.items()), peak_month=max(months, key=lambda mo: month_total[mo]))
132
+ return ans
133
+
134
+ if os.path.exists("activity_data.csv"): answer = activity()
135
+ elif os.path.exists("gwp_values.md"): answer = multigas()
136
+ elif os.path.exists("target.md"): answer = series()
137
+ else: answer = quality()
138
+ with open("answer.json", "w") as f: json.dump(answer, f, indent=1)
tasks/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-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 = "emissions-inventory"
8
+ tags = ["emissions-inventory", "activity-data", "isced-0521", "train"]
9
+ isced_f = "0521"
10
+ family = "activity-data"
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/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/checks.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "path": "by_source.business_flights",
4
+ "type": "number",
5
+ "value": 14.72,
6
+ "abs_tol": 0.01,
7
+ "weight": 1.0
8
+ },
9
+ {
10
+ "path": "by_source.diesel_fleet",
11
+ "type": "number",
12
+ "value": 85.29,
13
+ "abs_tol": 0.01,
14
+ "weight": 1.0
15
+ },
16
+ {
17
+ "path": "by_source.petrol_fleet",
18
+ "type": "number",
19
+ "value": 13.87,
20
+ "abs_tol": 0.01,
21
+ "weight": 1.0
22
+ },
23
+ {
24
+ "path": "by_source.purchased_electricity",
25
+ "type": "number",
26
+ "value": 150.7,
27
+ "abs_tol": 0.01,
28
+ "weight": 1.0
29
+ },
30
+ {
31
+ "path": "by_source.waste_to_landfill",
32
+ "type": "number",
33
+ "value": 32.06,
34
+ "abs_tol": 0.01,
35
+ "weight": 1.0
36
+ },
37
+ {
38
+ "path": "by_scope.scope_1",
39
+ "type": "number",
40
+ "value": 99.16,
41
+ "abs_tol": 0.01,
42
+ "weight": 1.0
43
+ },
44
+ {
45
+ "path": "by_scope.scope_2",
46
+ "type": "number",
47
+ "value": 150.7,
48
+ "abs_tol": 0.01,
49
+ "weight": 1.0
50
+ },
51
+ {
52
+ "path": "by_scope.scope_3",
53
+ "type": "number",
54
+ "value": 46.79,
55
+ "abs_tol": 0.01,
56
+ "weight": 1.0
57
+ },
58
+ {
59
+ "path": "total_t_co2e",
60
+ "type": "number",
61
+ "value": 296.65,
62
+ "abs_tol": 0.01,
63
+ "weight": 2
64
+ }
65
+ ]
tasks/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-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/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/activity_data.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ record_id,site,invoice_date,source,quantity,unit,supplier_ref
2
+ R001,head_office,2024-10-15,company_cars,43054,km,INV-43775
3
+ R002,head_office,2024-04-22,company_cars,62000,km,INV-13655
4
+ R003,head_office,2024-10-03,business_flights,15562,km,INV-16062
5
+ R004,head_office,2024-12-23,rail_travel,91361,km,INV-68149
6
+ R005,head_office,2024-12-13,company_cars,14862,mile,INV-98305
7
+ R006,head_office,2024-10-02,natural_gas,597860,kWh,INV-55612
8
+ R007,head_office,2024-09-21,district_heating,504.3,GJ,INV-73684
9
+ R008,head_office,2024-10-26,business_flights,6946,mile,INV-13938
10
+ R009,head_office,2024-08-23,district_heating,86573,kWh,INV-36898
11
+ R010,head_office,2024-04-17,district_heating,137740,kWh,INV-85481