diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..568720078e729340b66cd611ca8cb24fdc8c2752 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/activity_data.csv @@ -0,0 +1,10 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2019-03-25,purchased_electricity,194568,kWh,INV-88187 +R002,head_office,2019-12-24,district_heating,158051,kWh,INV-83456 +R003,head_office,2019-02-21,company_cars,147677,km,INV-42239 +R004,head_office,2019-04-28,purchased_electricity,170868,kWh,INV-24442 +R005,head_office,2019-12-06,rail_travel,3965,km,INV-68052 +R006,head_office,2019-04-07,rail_travel,7235,km,INV-29827 +R007,head_office,2019-09-14,purchased_electricity,159341,kWh,INV-44486 +R008,head_office,2019-06-24,company_cars,123619,km,INV-34130 +R009,head_office,2019-09-20,petrol_fleet,18651.1,litre,INV-13487 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..f1f8de21dcf1d4e93c9da9e3acdbe04387b88f5b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.154,km,3 +company_cars,0.179,km,1 +diesel_fleet,2.41,litre,1 +district_heating,0.0986,kWh,2 +heating_oil,2.71,litre,1 +natural_gas,0.182,kWh,1 +petrol_fleet,2.53,litre,1 +purchased_electricity,0.249,kWh,2 +rail_travel,0.0362,km,3 +waste_to_landfill,422.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..86739fd855013adc2d303c322eda1a882a3c0e1a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Lindqvist Castings +- Reporting year: 2019 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..c15b37f6d110ece6adb50a4526329e98de04980e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.59,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af55fd1fc7af9b95eb96a96e95695ae490618684 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2019 greenhouse-gas inventory for Lindqvist Castings (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2019 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..01492ca54f9a3208703ad4ddf2782dda1c5d9fe4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "eval"] +isced_f = "0521" +family = "activity-data" +split = "eval" +seed = 10000 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8e35c99dcc4ebf37ba7270557b82ecca85e616c2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.company_cars", + "type": "number", + "value": 48.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 15.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 47.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 130.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 0.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 95.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 146.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 0.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 242.41, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0000/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..8cc2757b197874abea9f24d9dccfd01b1bfaeace --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/activity_data.csv @@ -0,0 +1,15 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2020-09-24,heating_oil,1866.0,litre,INV-61458 +R002,head_office,2020-08-20,petrol_fleet,4018.3,litre,INV-32270 +R003,head_office,2020-10-04,purchased_electricity,316661,kWh,INV-63632 +R004,head_office,2020-06-20,heating_oil,2282.9,litre,INV-68354 +R005,head_office,2020-12-05,heating_oil,3926.2,litre,INV-26480 +R006,head_office,2020-04-21,purchased_electricity,215878,kWh,INV-12262 +R007,head_office,2020-02-14,business_flights,22312,km,INV-11253 +R008,head_office,2020-02-24,purchased_electricity,195090,kWh,INV-98331 +R009,head_office,2020-04-16,petrol_fleet,3529.3,litre,INV-85057 +R010,head_office,2020-10-26,company_cars,69310,mile,INV-31363 +R011,head_office,2020-09-12,business_flights,7672,km,INV-54916 +R012,head_office,2020-03-23,business_flights,15708,km,INV-58845 +R013,head_office,2020-01-28,petrol_fleet,3363.4,litre,INV-80171 +R014,head_office,2020-10-07,company_cars,106020,km,INV-38862 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..66e6e2983e6cae13dbc122305e6c4c70dcde404f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.155,km,3 +company_cars,0.183,km,1 +diesel_fleet,2.91,litre,1 +district_heating,0.0896,kWh,2 +heating_oil,2.52,litre,1 +natural_gas,0.174,kWh,1 +petrol_fleet,2.49,litre,1 +purchased_electricity,0.224,kWh,2 +rail_travel,0.0317,km,3 +waste_to_landfill,441.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..28e877ab8c65341dc5450fe2e9b8a5687d795e5f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Kestrel Joinery +- Reporting year: 2020 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..572f26007af84e22c0d4820fd7945cf5868737be --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.84,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..973dd7aa243dae7c2c3bdd521e2fe2fc8fb7b22f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2020 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2020 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..48aa5d8ff9e433e853899e22e2eead09e9d51ca3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "eval"] +isced_f = "0521" +family = "activity-data" +split = "eval" +seed = 10012 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4564739d1d3f71c125b42e7459bb7fd9d870a247 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 7.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 39.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 20.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 27.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 162.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 87.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 162.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 7.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 257.4, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-e0012/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..d7f4fcc251f15bc73d89a1fb32188027b09f4355 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/activity_data.csv @@ -0,0 +1,10 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2020-06-23,waste_to_landfill,26.71,tonne,INV-70192 +R002,head_office,2020-08-20,waste_to_landfill,21442,kg,INV-78053 +R003,head_office,2020-08-21,diesel_fleet,12465.6,litre,INV-34088 +R004,head_office,2020-12-25,district_heating,487.353,MWh,INV-99329 +R005,head_office,2020-02-24,rail_travel,174944,km,INV-74900 +R006,head_office,2020-04-02,purchased_electricity,880.236,MWh,INV-61680 +R007,head_office,2020-01-08,diesel_fleet,9336.4,litre,INV-28291 +R008,head_office,2020-10-05,waste_to_landfill,15.14,tonne,INV-93432 +R009,head_office,2020-02-06,diesel_fleet,8593.1,litre,INV-42114 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..26cc71144a8c09c3a368f4c6f59b284e0766b937 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.165,km,3 +company_cars,0.187,km,1 +diesel_fleet,2.44,litre,1 +district_heating,0.0915,kWh,2 +heating_oil,2.32,litre,1 +natural_gas,0.2,kWh,1 +petrol_fleet,2.34,litre,1 +purchased_electricity,0.231,kWh,2 +rail_travel,0.0382,km,3 +waste_to_landfill,484.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..0894ce6ab661a26282e62ff7b256c1d26d9422f8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Ostervik Bakery Group +- Reporting year: 2020 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..3300ee4eca2d159e8aa671af7e7715b3246e8ec7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.89,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9d146213f8a1f802b73486ca4f00a3ca83bee2f4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2020 greenhouse-gas inventory for Ostervik Bakery Group (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2020 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ba7ccce0fbc2e3ffbb5af25124522567f4f24b3e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 0 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..083a17d717f4cd62475963c86cb24cffdf3d0528 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 74.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 44.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 203.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 6.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 30.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 74.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 247.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 37.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 359.41, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0000/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..cd1bbccc8849a99a0d0f5541eb404824829be46d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/activity_data.csv @@ -0,0 +1,10 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2023-08-28,waste_to_landfill,20.06,tonne,INV-99397 +R002,head_office,2023-11-20,petrol_fleet,3188.3,litre,INV-49218 +R003,head_office,2023-08-14,diesel_fleet,29926.2,litre,INV-75638 +R004,head_office,2023-09-27,purchased_electricity,666822,kWh,INV-94147 +R005,head_office,2023-12-08,business_flights,58680,km,INV-54911 +R006,head_office,2023-11-08,petrol_fleet,2565.9,litre,INV-85580 +R007,head_office,2023-02-11,waste_to_landfill,26.07,tonne,INV-96796 +R008,head_office,2023-10-18,business_flights,28964,km,INV-91899 +R009,head_office,2023-07-25,waste_to_landfill,32075,kg,INV-95031 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..13e61c8476f1b5a04c94bc445f49cf5aa7e4b6aa --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.168,km,3 +company_cars,0.178,km,1 +diesel_fleet,2.85,litre,1 +district_heating,0.092,kWh,2 +heating_oil,2.4,litre,1 +natural_gas,0.178,kWh,1 +petrol_fleet,2.41,litre,1 +purchased_electricity,0.226,kWh,2 +rail_travel,0.0343,km,3 +waste_to_landfill,410.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..a10ff91b31d16fd07a96b7b801bd40e2938efb4f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Ostervik Bakery Group +- Reporting year: 2023 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..bbe4d4c2b01c15841b53e994e210785fc961d378 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.98,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d3e0d8236607e0202266bc03a057e86d0da60f0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2023 greenhouse-gas inventory for Ostervik Bakery Group (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2023 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b6e8a7dbfc108de56c20fa245d5612c0e23b5720 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 12 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e7f6f5d5b74f5e0db9bbb34e78a3174e94c3e69c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 14.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 85.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 13.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 150.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 32.06, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 99.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 150.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 46.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 296.65, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0012/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..d30aad4295f26c78a0811cbffce235d69e89d371 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/activity_data.csv @@ -0,0 +1,11 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2024-10-15,company_cars,43054,km,INV-43775 +R002,head_office,2024-04-22,company_cars,62000,km,INV-13655 +R003,head_office,2024-10-03,business_flights,15562,km,INV-16062 +R004,head_office,2024-12-23,rail_travel,91361,km,INV-68149 +R005,head_office,2024-12-13,company_cars,14862,mile,INV-98305 +R006,head_office,2024-10-02,natural_gas,597860,kWh,INV-55612 +R007,head_office,2024-09-21,district_heating,504.3,GJ,INV-73684 +R008,head_office,2024-10-26,business_flights,6946,mile,INV-13938 +R009,head_office,2024-08-23,district_heating,86573,kWh,INV-36898 +R010,head_office,2024-04-17,district_heating,137740,kWh,INV-85481 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..b5b47b8bc8f666db9ea1fef5dc078b45d4cb83dd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.162,km,3 +company_cars,0.164,km,1 +diesel_fleet,2.73,litre,1 +district_heating,0.105,kWh,2 +heating_oil,2.45,litre,1 +natural_gas,0.173,kWh,1 +petrol_fleet,2.41,litre,1 +purchased_electricity,0.232,kWh,2 +rail_travel,0.0372,km,3 +waste_to_landfill,463.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..aff62215a242eb9ae2b7388a53a6e56f5fc2cc86 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Kestrel Joinery +- Reporting year: 2024 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..a3e3635f9b93ba99b01e7f3c1ca9d905e2bbfeab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,11.17,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95779a2c19913b38f42ac6fa3fcee8320d45b005 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2024 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2024 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..115a7cc5c92934c9156d41a049aa3ff1a331f4de --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 24 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6d67834cec90276489df28729ed32a52c2b0e19e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 4.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 21.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 38.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 103.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 3.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 124.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 38.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 7.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 170.57, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0024/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..9dfe008a5cf8ec76e79105da20b559d8ba44fa44 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/activity_data.csv @@ -0,0 +1,14 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2024-11-25,natural_gas,29683,kWh,INV-50208 +R002,head_office,2024-01-11,company_cars,54332,km,INV-10215 +R003,head_office,2024-01-02,natural_gas,52165,kWh,INV-99498 +R004,head_office,2024-08-10,district_heating,256.1,GJ,INV-72195 +R005,head_office,2024-01-23,district_heating,126.839,MWh,INV-64284 +R006,head_office,2024-04-12,rail_travel,62112,km,INV-60696 +R007,head_office,2024-10-04,rail_travel,40197,km,INV-37437 +R008,head_office,2024-10-15,company_cars,81740,km,INV-52102 +R009,head_office,2024-04-20,waste_to_landfill,36.46,tonne,INV-25916 +R010,head_office,2024-03-05,natural_gas,34742,kWh,INV-15638 +R011,head_office,2024-01-22,rail_travel,57486,km,INV-44168 +R012,head_office,2024-05-23,district_heating,113095,kWh,INV-71475 +R013,head_office,2024-01-06,company_cars,68982,mile,INV-68641 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..6ea39e5744fcdeac85b686b0db9f3acb8410ccf2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.168,km,3 +company_cars,0.164,km,1 +diesel_fleet,2.45,litre,1 +district_heating,0.0981,kWh,2 +heating_oil,2.75,litre,1 +natural_gas,0.182,kWh,1 +petrol_fleet,2.53,litre,1 +purchased_electricity,0.22,kWh,2 +rail_travel,0.0324,km,3 +waste_to_landfill,465.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..eee205d97f85282d8899d1652605653d3cded57a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Vessby Dairy Cooperative +- Reporting year: 2024 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..6e8ca919fff9378be5bfac487b8bedee721a6e2f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.57,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c897d3e4b401def583ee6f1fd6a5e1fa2e4a3c96 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2024 greenhouse-gas inventory for Vessby Dairy Cooperative (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2024 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c179be997a3dbd8dc3b986077c950a798b7ea01 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 36 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..df7853f80f3a8fd85aca1f49e89146b27fb6fea9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.company_cars", + "type": "number", + "value": 40.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 30.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 21.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 5.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 16.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 61.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 30.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 22.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 114.39, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0036/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..aa0bcc2c26d22abfc294672ebcabcf48142bba50 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/activity_data.csv @@ -0,0 +1,12 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2019-04-14,district_heating,190931,kWh,INV-21736 +R002,head_office,2019-02-27,company_cars,30611,mile,INV-99364 +R003,head_office,2019-07-25,rail_travel,29194,km,INV-27470 +R004,head_office,2019-05-12,petrol_fleet,15723.1,litre,INV-42734 +R005,head_office,2019-03-07,company_cars,40762,km,INV-44948 +R006,head_office,2019-02-26,rail_travel,27652,km,INV-34077 +R007,head_office,2019-06-07,diesel_fleet,12491.3,litre,INV-37098 +R008,head_office,2019-11-09,diesel_fleet,8.288,m3,INV-85696 +R009,head_office,2019-02-13,diesel_fleet,7.869,m3,INV-55852 +R010,head_office,2019-08-19,rail_travel,28686,km,INV-43247 +R011,head_office,2019-10-28,district_heating,188.387,MWh,INV-72871 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..b818c89bde15a9a15c6992626ce18896ce3def40 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.172,km,3 +company_cars,0.17,km,1 +diesel_fleet,2.58,litre,1 +district_heating,0.0886,kWh,2 +heating_oil,2.52,litre,1 +natural_gas,0.194,kWh,1 +petrol_fleet,2.47,litre,1 +purchased_electricity,0.243,kWh,2 +rail_travel,0.0348,km,3 +waste_to_landfill,441.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..342ebc13516759ad1fdc11c58c6aca5f8d1ef4be --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Marrow Vale Housing +- Reporting year: 2019 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..5117d9785b818c9fb873cd87220a524c4bece31a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.79,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e740b06bc55d33352a886d5ed51d02e64255e38d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2019 greenhouse-gas inventory for Marrow Vale Housing (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2019 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..37f6ed77a0d579aaaeaba5f98287854040c9cc5c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 48 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6fd007fd3cc1a05480526103fe49157340f27a4d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.company_cars", + "type": "number", + "value": 15.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 73.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 33.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 38.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 2.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 128.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 33.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 2.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 164.64, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0048/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..aeb9f2f3111be14a06e470f13bbff677fb6d9fa0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/activity_data.csv @@ -0,0 +1,12 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2020-10-06,purchased_electricity,183498,kWh,INV-87619 +R002,head_office,2020-11-11,heating_oil,8223.0,litre,INV-57568 +R003,head_office,2020-09-13,purchased_electricity,144030,kWh,INV-58856 +R004,head_office,2020-10-12,heating_oil,5161.3,litre,INV-94318 +R005,head_office,2020-05-06,waste_to_landfill,7036,kg,INV-70334 +R006,head_office,2020-05-15,business_flights,49938,km,INV-51913 +R007,head_office,2020-03-13,business_flights,38714,mile,INV-82167 +R008,head_office,2020-06-25,waste_to_landfill,9.99,tonne,INV-54035 +R009,head_office,2020-08-07,waste_to_landfill,10.54,tonne,INV-81115 +R010,head_office,2020-11-28,natural_gas,588952,kWh,INV-84116 +R011,head_office,2020-02-11,heating_oil,9011.5,litre,INV-13228 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..6236ccd422b1eceb326cf246f828bdf80a82e27e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.153,km,3 +company_cars,0.159,km,1 +diesel_fleet,2.67,litre,1 +district_heating,0.0968,kWh,2 +heating_oil,2.42,litre,1 +natural_gas,0.175,kWh,1 +petrol_fleet,2.1,litre,1 +purchased_electricity,0.216,kWh,2 +rail_travel,0.037,km,3 +waste_to_landfill,467.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..2fe629261953c1bbac50c2c834f96d4c795ece4e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Harlow Fold Logistics +- Reporting year: 2020 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..5117d9785b818c9fb873cd87220a524c4bece31a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.79,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6204d07954ecdc40260ec55797357d37f357a8c2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2020 greenhouse-gas inventory for Harlow Fold Logistics (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2020 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49c9f320be9db1a1e53d664cb249828f472dc696 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 60 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d950b3af6abac7545d61effb034ea2d5be4e17b1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 17.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 54.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 103.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 70.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 12.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 157.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 70.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 30.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 258.06, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0060/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..3d4421709157116d5ab264f8f0672bd61e3bed39 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/activity_data.csv @@ -0,0 +1,11 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2019-05-01,diesel_fleet,37820.8,litre,INV-28903 +R002,head_office,2019-05-28,business_flights,102030,km,INV-34585 +R003,head_office,2019-09-26,business_flights,125862,km,INV-34905 +R004,head_office,2019-03-20,purchased_electricity,84.69,MWh,INV-10670 +R005,head_office,2019-11-08,purchased_electricity,208.374,MWh,INV-91296 +R006,head_office,2019-12-15,natural_gas,232.324,MWh,INV-35124 +R007,head_office,2019-02-25,purchased_electricity,179552,kWh,INV-20155 +R008,head_office,2019-11-14,natural_gas,208.68,MWh,INV-91609 +R009,head_office,2019-08-09,natural_gas,98519,kWh,INV-77161 +R010,head_office,2019-09-25,heating_oil,18563.0,litre,INV-42478 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..dd8871282ac7aabf4adec3d7fa5b2be3e17f09f3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.166,km,3 +company_cars,0.163,km,1 +diesel_fleet,2.71,litre,1 +district_heating,0.103,kWh,2 +heating_oil,2.74,litre,1 +natural_gas,0.2,kWh,1 +petrol_fleet,2.34,litre,1 +purchased_electricity,0.236,kWh,2 +rail_travel,0.038,km,3 +waste_to_landfill,467.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..cb6be5820538da8085b54528dea94d925baa4f80 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Ostervik Bakery Group +- Reporting year: 2019 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..86dff3e2d9f34e7d6b252b631380d8bd7902de4a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.99,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bc21ce15c99d0905d976e45e37bcef29b85a87b0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: activity data + +You are compiling the 2019 greenhouse-gas inventory for Ostervik Bakery Group (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +Every record belongs to the 2019 reporting year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f156d1ad7a0c6bb742b4cdd97a37538cc0cb1ca0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 72 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f0dfc6fbd574f2c5144d75cb0de2325d4b658bea --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/checks.json @@ -0,0 +1,65 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 37.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 102.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 50.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 107.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 111.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 261.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 111.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 37.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 410.63, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d1-t0072/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..09b344a4855e70fc710f666d7ae874ebbf01fd6e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/activity_data.csv @@ -0,0 +1,29 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,depot,2021-06-20,petrol_fleet,2399.4,litre,INV-89074 +R002,warehouse,2022-02-20,district_heating,375.2,GJ,INV-72920 +R003,head_office,2021-09-18,district_heating,65.507,MWh,INV-88413 +R004,head_office,2021-05-02,rail_travel,8244,km,INV-92932 +R005,head_office,2020-12-16,rail_travel,26794,km,INV-31167 +R006,depot,2021-12-09,district_heating,77.728,MWh,INV-78645 +R007,depot,2021-02-07,waste_to_landfill,1.1,tonne,INV-70775 +R008,warehouse,2021-09-28,waste_to_landfill,1183,kg,INV-89605 +R009,warehouse,2021-01-18,business_flights,41178,km,INV-57130 +R010,head_office,2020-11-11,heating_oil,3.862,m3,INV-21415 +R011,head_office,2021-07-20,heating_oil,8726.2,litre,INV-42363 +R012,head_office,2021-04-22,waste_to_landfill,1.7,tonne,INV-15506 +R013,depot,2021-09-15,business_flights,47300,km,INV-69146 +R014,head_office,2021-10-08,district_heating,264.0,GJ,INV-47236 +R015,warehouse,2022-01-22,petrol_fleet,2109.8,litre,INV-37325 +R016,warehouse,2021-09-03,district_heating,337.0,GJ,INV-12447 +R017,depot,2021-01-20,natural_gas,177485,kWh,INV-79879 +R018,head_office,2021-11-05,rail_travel,6713,km,INV-76040 +R019,warehouse,2021-09-07,waste_to_landfill,1.3,tonne,INV-54423 +R020,depot,2021-12-24,business_flights,29209,mile,INV-96568 +R021,depot,2021-09-28,petrol_fleet,5041.1,litre,INV-39721 +R022,depot,2021-08-19,heating_oil,5.311,m3,INV-62673 +R023,warehouse,2021-07-18,natural_gas,103.149,MWh,INV-54059 +R024,head_office,2021-12-16,business_flights,41374,km,INV-31609 +R025,warehouse,2021-09-27,rail_travel,13178,km,INV-46574 +R026,warehouse,2021-06-08,natural_gas,226.18,MWh,INV-10819 +R027,depot,2020-11-08,waste_to_landfill,16.73,tonne,INV-82223 +R028,depot,2021-02-26,heating_oil,5.538,m3,INV-60417 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..e79b4c35f1c0f2bb635147274ac8a07ce99ab507 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.169,km,3 +company_cars,0.165,km,1 +diesel_fleet,2.92,litre,1 +district_heating,0.0962,kWh,2 +heating_oil,2.47,litre,1 +natural_gas,0.193,kWh,1 +petrol_fleet,2.11,litre,1 +purchased_electricity,0.242,kWh,2 +rail_travel,0.0339,km,3 +waste_to_landfill,425.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..ef4af101f6851f9979e4440e7da46318ec1ffdd6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Marrow Vale Housing +- Reporting year: 2021 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..531029d6fc40ccaebf15ea7bc10fd4ff48b20e85 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.72,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2947eef0c4506c2bb2fd3847de4fb8b72622d640 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2021 greenhouse-gas inventory for Marrow Vale Housing (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2021 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..385d9a8843b0a83b3d72f91923cdf013aa5971e8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "eval"] +isced_f = "0521" +family = "activity-data" +split = "eval" +seed = 10004 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8748a6c264b6494afb377d31cf8694b3fcdcc1ad --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/checks.json @@ -0,0 +1,100 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 29.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 29.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 48.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 97.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 15.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 0.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 2.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 161.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 29.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 33.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 224.79, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 100.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 43.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 81.03, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0004/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..7e6d72fef1dfefb4382833016631ae3641a98ab1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/activity_data.csv @@ -0,0 +1,27 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,workshop,2020-03-06,diesel_fleet,6.438,m3,INV-87074 +R002,depot,2020-04-13,company_cars,25684,mile,INV-39142 +R003,workshop,2020-06-23,petrol_fleet,8907.7,litre,INV-28789 +R004,depot,2021-02-19,company_cars,24910,mile,INV-37066 +R005,workshop,2019-12-16,business_flights,3629,mile,INV-33207 +R006,depot,2020-07-06,diesel_fleet,5.231,m3,INV-64126 +R007,workshop,2020-04-19,company_cars,15431,mile,INV-81090 +R008,depot,2020-01-24,petrol_fleet,7583.0,litre,INV-97846 +R009,head_office,2019-11-19,petrol_fleet,4361.5,litre,INV-16887 +R010,head_office,2020-07-02,natural_gas,118.313,MWh,INV-41114 +R011,workshop,2020-01-24,natural_gas,9406.454,m3,INV-61541 +R012,depot,2020-02-07,waste_to_landfill,26.07,tonne,INV-93413 +R013,depot,2021-02-10,business_flights,56708,mile,INV-12645 +R014,head_office,2020-11-09,business_flights,211745,km,INV-58126 +R015,workshop,2020-11-13,district_heating,31126,kWh,INV-22161 +R016,head_office,2020-06-05,diesel_fleet,3469.0,litre,INV-49753 +R017,workshop,2020-09-26,diesel_fleet,5654.7,litre,INV-28859 +R018,workshop,2020-12-28,business_flights,99112,mile,INV-46588 +R019,workshop,2020-05-03,waste_to_landfill,19.7,tonne,INV-85830 +R020,workshop,2019-11-26,natural_gas,103175,kWh,INV-37590 +R021,workshop,2020-12-04,natural_gas,114719,kWh,INV-65037 +R022,head_office,2020-07-17,district_heating,76.8,GJ,INV-78408 +R023,workshop,2020-02-01,company_cars,38302,km,INV-81269 +R024,head_office,2020-10-22,waste_to_landfill,11.61,tonne,INV-36715 +R025,workshop,2020-05-15,waste_to_landfill,25302,kg,INV-79421 +R026,head_office,2020-10-09,natural_gas,80737,kWh,INV-34300 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..454d43bcf1d9780fcc0f9f887f53bea219143a05 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.172,km,3 +company_cars,0.169,km,1 +diesel_fleet,2.44,litre,1 +district_heating,0.102,kWh,2 +heating_oil,2.35,litre,1 +natural_gas,0.199,kWh,1 +petrol_fleet,2.15,litre,1 +purchased_electricity,0.215,kWh,2 +rail_travel,0.0357,km,3 +waste_to_landfill,432.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..2fe629261953c1bbac50c2c834f96d4c795ece4e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Harlow Fold Logistics +- Reporting year: 2020 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..86dff3e2d9f34e7d6b252b631380d8bd7902de4a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.99,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f0349be26497bde9f891c42024e23826482a50e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2020 greenhouse-gas inventory for Harlow Fold Logistics (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2020 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..78b28ab98126768b08bef958bdaa0d10a14aa46f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "eval"] +isced_f = "0521" +family = "activity-data" +split = "eval" +seed = 10016 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b4ec8216e17776278175f123a37c59ac64c2b055 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/checks.json @@ -0,0 +1,100 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 63.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 17.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 50.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 5.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 83.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 35.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 35.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 186.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 5.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 99.57, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 291.78, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 47.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 91.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 152.78, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-e0016/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..c92c82cb7bd8b7c8123776e056716990ff16d98e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/activity_data.csv @@ -0,0 +1,26 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,depot,2023-04-13,purchased_electricity,52.918,MWh,INV-43927 +R002,head_office,2023-11-22,purchased_electricity,22752,kWh,INV-19006 +R003,head_office,2023-05-28,company_cars,60976,km,INV-82164 +R004,head_office,2023-10-03,diesel_fleet,7.167,m3,INV-95456 +R005,depot,2023-07-19,petrol_fleet,10664.5,litre,INV-36291 +R006,depot,2023-12-26,district_heating,357.1,GJ,INV-72400 +R007,head_office,2023-11-07,district_heating,48.403,MWh,INV-52949 +R008,head_office,2023-01-26,petrol_fleet,6763.0,litre,INV-78855 +R009,head_office,2023-11-14,rail_travel,28227,km,INV-54240 +R010,warehouse,2023-04-28,purchased_electricity,36064,kWh,INV-34815 +R011,head_office,2023-10-19,company_cars,76790,km,INV-55304 +R012,depot,2022-12-06,purchased_electricity,98809,kWh,INV-59792 +R013,depot,2023-09-19,company_cars,54584,km,INV-84047 +R014,head_office,2023-04-06,natural_gas,249344,kWh,INV-99359 +R015,depot,2023-12-10,rail_travel,49239,km,INV-13043 +R016,head_office,2024-02-02,purchased_electricity,195.481,MWh,INV-68990 +R017,depot,2023-05-15,diesel_fleet,7.682,m3,INV-75312 +R018,depot,2023-05-17,natural_gas,97.011,MWh,INV-88307 +R019,warehouse,2024-02-27,district_heating,61363,kWh,INV-89427 +R020,head_office,2023-05-12,rail_travel,25438,km,INV-34025 +R021,warehouse,2022-12-07,petrol_fleet,4255.6,litre,INV-21824 +R022,warehouse,2023-04-12,company_cars,72797,km,INV-89358 +R023,head_office,2022-11-16,rail_travel,10604,km,INV-57126 +R024,depot,2023-01-21,district_heating,110102,kWh,INV-99919 +R025,depot,2023-09-18,purchased_electricity,25.328,MWh,INV-91169 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..34c2106c03a645a6fcb044f171bd6cf6f1f40810 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.159,km,3 +company_cars,0.184,km,1 +diesel_fleet,2.84,litre,1 +district_heating,0.0982,kWh,2 +heating_oil,2.63,litre,1 +natural_gas,0.173,kWh,1 +petrol_fleet,2.28,litre,1 +purchased_electricity,0.219,kWh,2 +rail_travel,0.0321,km,3 +waste_to_landfill,456.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..767422bc0e19db2651cf1cde40b7bd15b359f0e9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Lindqvist Castings +- Reporting year: 2023 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..8689cd5dab2ea2a6860e4b3ed6bb972489965dac --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.44,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8c7f0b5c9e596247d346f7fa5f08d6de98c885d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2023 greenhouse-gas inventory for Lindqvist Castings (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2023 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..55d4522c923a4cfbd5fd4fdab35501421a323770 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 4 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ef12f39559981120c494bb2734781baa5ec4d370 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/checks.json @@ -0,0 +1,100 @@ +[ + { + "path": "by_source.company_cars", + "type": "number", + "value": 48.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 42.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 25.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 59.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 39.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 30.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 3.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 190.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 55.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 3.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 249.24, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 112.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 115.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 21.29, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0004/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..f650c7b79faa0d2476a55b0fc058a52ac79880e2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/activity_data.csv @@ -0,0 +1,23 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,depot,2020-07-02,diesel_fleet,11.999,m3,INV-56880 +R002,depot,2020-03-05,diesel_fleet,7951.8,litre,INV-48853 +R003,depot,2020-04-11,natural_gas,11904.011,m3,INV-71774 +R004,depot,2020-09-14,purchased_electricity,24.876,MWh,INV-36783 +R005,workshop,2020-08-14,waste_to_landfill,33.75,tonne,INV-69523 +R006,depot,2019-12-17,natural_gas,14066.965,m3,INV-93095 +R007,depot,2020-02-15,petrol_fleet,737.5,litre,INV-48917 +R008,workshop,2021-01-15,purchased_electricity,93.133,MWh,INV-57367 +R009,depot,2020-08-05,rail_travel,97420,km,INV-99720 +R010,workshop,2020-07-05,petrol_fleet,940.6,litre,INV-95429 +R011,depot,2020-01-02,purchased_electricity,24061,kWh,INV-22144 +R012,depot,2020-02-19,petrol_fleet,679.2,litre,INV-54728 +R013,workshop,2021-01-15,diesel_fleet,4929.2,litre,INV-97699 +R014,depot,2020-10-15,rail_travel,70595,km,INV-83000 +R015,depot,2020-01-17,natural_gas,4299.903,m3,INV-83702 +R016,depot,2020-07-10,diesel_fleet,15.85,m3,INV-32661 +R017,depot,2020-07-07,heating_oil,3711.6,litre,INV-75441 +R018,workshop,2020-06-10,petrol_fleet,1226.2,litre,INV-60479 +R019,depot,2020-07-01,heating_oil,7843.4,litre,INV-90990 +R020,depot,2020-10-09,waste_to_landfill,32419,kg,INV-63111 +R021,workshop,2020-02-01,purchased_electricity,38037,kWh,INV-52571 +R022,workshop,2020-08-01,heating_oil,8131.1,litre,INV-17668 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..9e19cd7b66c31f6ff2a4c8a2a836fdc29278475b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.158,km,3 +company_cars,0.174,km,1 +diesel_fleet,2.89,litre,1 +district_heating,0.0887,kWh,2 +heating_oil,2.31,litre,1 +natural_gas,0.178,kWh,1 +petrol_fleet,2.17,litre,1 +purchased_electricity,0.211,kWh,2 +rail_travel,0.0334,km,3 +waste_to_landfill,459.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..2fe629261953c1bbac50c2c834f96d4c795ece4e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Harlow Fold Logistics +- Reporting year: 2020 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..7da50a4c72e9f6736ae8f522573d45a3b95e103f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.55,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f0349be26497bde9f891c42024e23826482a50e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2020 greenhouse-gas inventory for Harlow Fold Logistics (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2020 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4b5406d7ebe4aa0756d9e76f82d62c228cd36c3e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 16 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..0dc1a2e39242c0535cc0b37e2fc39a8f1a01b9a7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/checks.json @@ -0,0 +1,93 @@ +[ + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 103.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 45.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 30.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 7.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 18.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 5.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 30.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 187.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 18.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 35.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 241.48, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 194.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 47.0, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0016/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..346f9b749bd122dae93e48b283db5deb5cae2563 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/activity_data.csv @@ -0,0 +1,26 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2023-10-12,company_cars,19924,mile,INV-13647 +R002,depot,2023-08-23,company_cars,22551,km,INV-91146 +R003,depot,2022-11-26,natural_gas,1426.167,m3,INV-76120 +R004,depot,2023-05-05,district_heating,46.535,MWh,INV-69994 +R005,warehouse,2023-02-11,natural_gas,4250.454,m3,INV-10746 +R006,head_office,2023-09-25,district_heating,116478,kWh,INV-63249 +R007,depot,2023-01-05,rail_travel,9554,km,INV-12472 +R008,head_office,2023-09-12,petrol_fleet,1903.7,litre,INV-14443 +R009,head_office,2023-07-28,diesel_fleet,3.482,m3,INV-19524 +R010,head_office,2023-06-26,diesel_fleet,4.993,m3,INV-35931 +R011,head_office,2023-03-17,purchased_electricity,383019,kWh,INV-61570 +R012,head_office,2023-05-22,natural_gas,41.067,MWh,INV-40962 +R013,depot,2023-11-12,rail_travel,15254,km,INV-41608 +R014,depot,2023-01-23,district_heating,57647,kWh,INV-80908 +R015,head_office,2023-02-13,petrol_fleet,2970.4,litre,INV-50189 +R016,warehouse,2023-04-21,petrol_fleet,1600.2,litre,INV-96978 +R017,depot,2023-07-21,company_cars,17318,km,INV-74946 +R018,head_office,2023-06-06,purchased_electricity,411574,kWh,INV-49238 +R019,depot,2023-09-16,district_heating,108.521,MWh,INV-70640 +R020,warehouse,2023-01-19,diesel_fleet,5.17,m3,INV-92419 +R021,depot,2022-11-25,rail_travel,26685,km,INV-14045 +R022,depot,2022-11-28,purchased_electricity,169.228,MWh,INV-65814 +R023,head_office,2023-03-25,diesel_fleet,3820.5,litre,INV-16393 +R024,warehouse,2023-05-03,natural_gas,98.384,MWh,INV-73290 +R025,depot,2023-06-05,natural_gas,86.189,MWh,INV-91934 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..3716772be2bdf971978464c423e824fbcea976b6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.161,km,3 +company_cars,0.158,km,1 +diesel_fleet,2.81,litre,1 +district_heating,0.103,kWh,2 +heating_oil,2.39,litre,1 +natural_gas,0.188,kWh,1 +petrol_fleet,2.15,litre,1 +purchased_electricity,0.249,kWh,2 +rail_travel,0.0372,km,3 +waste_to_landfill,449.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..36988cb9f11f0db841975bf2eceeab42632574b1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Vessby Dairy Cooperative +- Reporting year: 2023 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..9c6b4c28749daefa4d77c32d854388ab5bc5c26a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.64,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..42c68b4283bc458b6f7dd8a991e74387c4b588cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2023 greenhouse-gas inventory for Vessby Dairy Cooperative (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2023 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..adc97163dbab0cd654443b043c6d7a802a44f512 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 28 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..369c5e6ea477990527216e695e19cc352c701735 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/checks.json @@ -0,0 +1,100 @@ +[ + { + "path": "by_source.company_cars", + "type": "number", + "value": 11.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 49.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 33.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 50.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 13.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 197.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 0.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 125.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 231.76, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 0.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 357.97, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 45.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 267.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 44.97, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0028/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..1f56bb44c744fb6bc417790cb646cb13850f3495 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/activity_data.csv @@ -0,0 +1,24 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,workshop,2021-05-07,diesel_fleet,6.533,m3,INV-67438 +R002,depot,2021-02-15,rail_travel,48598,km,INV-62465 +R003,depot,2022-01-12,petrol_fleet,1616.3,litre,INV-77274 +R004,workshop,2021-02-17,natural_gas,68080,kWh,INV-23105 +R005,depot,2021-12-28,district_heating,77483,kWh,INV-65249 +R006,depot,2020-12-10,rail_travel,43242,km,INV-20533 +R007,depot,2021-10-22,heating_oil,3997.4,litre,INV-62960 +R008,workshop,2020-11-26,rail_travel,16611,km,INV-10908 +R009,depot,2021-11-02,diesel_fleet,3532.4,litre,INV-63896 +R010,workshop,2020-12-07,district_heating,71943,kWh,INV-64080 +R011,workshop,2021-10-24,heating_oil,5.254,m3,INV-16825 +R012,depot,2021-09-13,heating_oil,2374.9,litre,INV-94247 +R013,workshop,2021-04-11,diesel_fleet,6.697,m3,INV-58898 +R014,depot,2021-09-05,rail_travel,22582,km,INV-44620 +R015,depot,2021-06-14,waste_to_landfill,42.27,tonne,INV-17045 +R016,workshop,2021-10-25,heating_oil,5274.8,litre,INV-55760 +R017,workshop,2021-11-16,waste_to_landfill,43235,kg,INV-20201 +R018,depot,2021-07-25,petrol_fleet,3136.2,litre,INV-12826 +R019,depot,2021-10-03,district_heating,48.74,MWh,INV-25528 +R020,workshop,2021-07-08,natural_gas,54099,kWh,INV-22263 +R021,depot,2021-04-08,district_heating,69908,kWh,INV-37260 +R022,depot,2021-03-17,natural_gas,71671,kWh,INV-50005 +R023,workshop,2021-02-20,petrol_fleet,2728.1,litre,INV-97329 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..434fd9b009a0f9b74c8ee50458a9bab752b113c2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.15,km,3 +company_cars,0.165,km,1 +diesel_fleet,2.69,litre,1 +district_heating,0.107,kWh,2 +heating_oil,2.56,litre,1 +natural_gas,0.184,kWh,1 +petrol_fleet,2.49,litre,1 +purchased_electricity,0.218,kWh,2 +rail_travel,0.0371,km,3 +waste_to_landfill,450.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..e8fb41220b7707051346effea97fda992f3e2ec7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Kestrel Joinery +- Reporting year: 2021 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..6ea452e0dc23d440c87f64e991667c0b8c00504c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.7,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8cff8234a9a55fe11066ff4bd9f14f099da9925d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2021 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2021 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..29beeac37028b4a07b3786283ecf4e257e422b6a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 40 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..421162098aeb43b1aed8ae2d6899bce8571111f1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/checks.json @@ -0,0 +1,93 @@ +[ + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 45.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 20.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 43.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 35.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 14.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 2.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 38.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 138.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 20.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 41.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 200.73, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 89.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 111.27, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0040/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..ff7b1d6f4f369902cbde64bf6d730886f5e4ff15 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/activity_data.csv @@ -0,0 +1,23 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,warehouse,2023-12-10,purchased_electricity,60869,kWh,INV-61754 +R002,warehouse,2023-10-12,diesel_fleet,13119.4,litre,INV-78404 +R003,workshop,2023-11-07,natural_gas,111860,kWh,INV-60122 +R004,workshop,2023-09-10,business_flights,175115,km,INV-91924 +R005,warehouse,2023-12-14,waste_to_landfill,18.78,tonne,INV-86502 +R006,warehouse,2023-09-02,natural_gas,12070.401,m3,INV-33191 +R007,workshop,2023-09-25,natural_gas,154.917,MWh,INV-53716 +R008,warehouse,2023-10-25,waste_to_landfill,11516,kg,INV-95327 +R009,workshop,2023-05-07,purchased_electricity,30.064,MWh,INV-81845 +R010,workshop,2023-09-02,purchased_electricity,50.936,MWh,INV-71236 +R011,warehouse,2023-10-05,waste_to_landfill,24049,kg,INV-13292 +R012,warehouse,2023-08-16,purchased_electricity,60470,kWh,INV-94589 +R013,workshop,2024-01-26,waste_to_landfill,13.86,tonne,INV-98780 +R014,warehouse,2022-11-10,natural_gas,10728.953,m3,INV-62502 +R015,workshop,2023-01-23,diesel_fleet,5529.5,litre,INV-69701 +R016,workshop,2023-03-25,business_flights,206067,km,INV-45324 +R017,warehouse,2023-07-04,company_cars,36506,mile,INV-34172 +R018,workshop,2023-05-18,company_cars,18301,mile,INV-40304 +R019,warehouse,2023-11-14,district_heating,48.147,MWh,INV-25090 +R020,workshop,2023-11-16,district_heating,61311,kWh,INV-75018 +R021,warehouse,2022-11-22,business_flights,20486,mile,INV-70502 +R022,warehouse,2023-04-28,district_heating,50183,kWh,INV-98581 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..cda798f839dec497bc33dab4e77854334985823c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.143,km,3 +company_cars,0.158,km,1 +diesel_fleet,2.42,litre,1 +district_heating,0.107,kWh,2 +heating_oil,2.31,litre,1 +natural_gas,0.186,kWh,1 +petrol_fleet,2.1,litre,1 +purchased_electricity,0.23,kWh,2 +rail_travel,0.0332,km,3 +waste_to_landfill,444.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..7366f4052a1017a2d6a61de0a736b21cf83dea27 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Tarnwick Borough Council +- Reporting year: 2023 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..836d44a614f1579c71978f4228edfdec564e6ae8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.5,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f5905c6f2fb5b27b798b31f41d6ee61aea2eb14 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2023 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2023 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f7e135408bb357fe36736090caf880c0478619bf --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 52 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b7dcabac2f6f08e839c0a4fa8001cd57943c4f71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/checks.json @@ -0,0 +1,93 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 54.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 13.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 45.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 17.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 73.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 46.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 24.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 132.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 63.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 78.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 274.52, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 127.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 147.35, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0052/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..9e9c790ca7b73e7d98d2497450cda5ee608dd7d8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/activity_data.csv @@ -0,0 +1,25 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2020-11-25,waste_to_landfill,12562,kg,INV-41766 +R002,head_office,2020-07-25,heating_oil,7.947,m3,INV-38245 +R003,head_office,2020-02-24,district_heating,146743,kWh,INV-50361 +R004,warehouse,2020-08-16,purchased_electricity,222.804,MWh,INV-72617 +R005,warehouse,2020-08-04,company_cars,33444,mile,INV-13940 +R006,head_office,2019-12-17,company_cars,32338,km,INV-43284 +R007,warehouse,2021-01-13,company_cars,60520,km,INV-90675 +R008,head_office,2020-04-22,business_flights,4164,mile,INV-66052 +R009,warehouse,2020-04-10,purchased_electricity,230576,kWh,INV-33386 +R010,head_office,2020-06-26,business_flights,5262,mile,INV-69616 +R011,head_office,2020-05-27,company_cars,37702,km,INV-72782 +R012,head_office,2020-09-28,business_flights,7768,km,INV-92999 +R013,warehouse,2020-01-26,waste_to_landfill,25.17,tonne,INV-75060 +R014,warehouse,2020-02-13,petrol_fleet,5237.2,litre,INV-97134 +R015,head_office,2020-10-01,petrol_fleet,5040.1,litre,INV-92856 +R016,warehouse,2021-02-06,waste_to_landfill,27272,kg,INV-48117 +R017,warehouse,2020-04-27,company_cars,35548,km,INV-69782 +R018,warehouse,2020-09-25,heating_oil,8870.7,litre,INV-19140 +R019,head_office,2020-06-25,purchased_electricity,101081,kWh,INV-62796 +R020,warehouse,2020-10-10,district_heating,287.3,GJ,INV-38104 +R021,head_office,2020-01-21,waste_to_landfill,35980,kg,INV-36622 +R022,head_office,2020-08-03,heating_oil,12852.0,litre,INV-90096 +R023,head_office,2020-10-23,petrol_fleet,2354.9,litre,INV-53628 +R024,head_office,2019-12-20,business_flights,60115,mile,INV-49597 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..16ae0e10ded8e38b71bce2df3e7f7fee0002e678 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.154,km,3 +company_cars,0.18,km,1 +diesel_fleet,2.59,litre,1 +district_heating,0.0986,kWh,2 +heating_oil,2.37,litre,1 +natural_gas,0.188,kWh,1 +petrol_fleet,2.17,litre,1 +purchased_electricity,0.214,kWh,2 +rail_travel,0.0378,km,3 +waste_to_landfill,450.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..41c557f00fc3f72a53af1b2a3d30cc57243e73fc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Vessby Dairy Cooperative +- Reporting year: 2020 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..45490493de7bd6fc8ab10c3cfaa2da5b9c1f4c9f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.87,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff03849333e85b3f6a6dbe5812abc31e95db1bd1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2020 greenhouse-gas inventory for Vessby Dairy Cooperative (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2020 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..29f5d16fb60da9f190fcc6c4c3a3a5f70078e2f4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 64 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..0240a0f61bb847219ce6074969318bd0a0222118 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/checks.json @@ -0,0 +1,93 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 3.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 22.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 22.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 70.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 27.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 118.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 33.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 120.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 140.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 36.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 298.3, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 133.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 164.69, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0064/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..2998b580bd1f7239e989facb0e098b37a4129dcb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/activity_data.csv @@ -0,0 +1,27 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,workshop,2024-11-17,heating_oil,8.693,m3,INV-62576 +R002,workshop,2024-06-18,rail_travel,25330,km,INV-27837 +R003,depot,2024-08-03,diesel_fleet,8.416,m3,INV-75733 +R004,workshop,2024-01-09,natural_gas,4307.49,m3,INV-23914 +R005,depot,2024-10-11,district_heating,15564,kWh,INV-36189 +R006,depot,2024-08-13,petrol_fleet,2095.5,litre,INV-92124 +R007,depot,2023-11-17,rail_travel,46434,km,INV-55654 +R008,depot,2024-11-08,company_cars,38866,mile,INV-73999 +R009,depot,2024-11-01,heating_oil,9.145,m3,INV-84443 +R010,workshop,2024-10-12,company_cars,73650,mile,INV-22390 +R011,depot,2024-12-25,rail_travel,29265,km,INV-76260 +R012,workshop,2023-11-11,petrol_fleet,3002.8,litre,INV-51866 +R013,depot,2024-10-21,petrol_fleet,1433.5,litre,INV-95956 +R014,depot,2024-01-01,natural_gas,70.916,MWh,INV-75081 +R015,depot,2024-04-06,district_heating,26369,kWh,INV-58596 +R016,depot,2024-07-17,petrol_fleet,3679.2,litre,INV-55766 +R017,workshop,2024-07-10,natural_gas,83.274,MWh,INV-65909 +R018,workshop,2023-12-10,district_heating,283.5,GJ,INV-23014 +R019,depot,2024-02-15,rail_travel,15816,km,INV-56941 +R020,workshop,2024-10-10,diesel_fleet,10042.2,litre,INV-48527 +R021,depot,2023-12-09,heating_oil,1991.1,litre,INV-54513 +R022,workshop,2024-02-15,natural_gas,53932,kWh,INV-50776 +R023,depot,2024-12-14,diesel_fleet,4734.2,litre,INV-42675 +R024,depot,2024-07-18,district_heating,43.0,GJ,INV-21562 +R025,depot,2024-07-07,heating_oil,9.679,m3,INV-94267 +R026,depot,2024-01-01,petrol_fleet,2793.3,litre,INV-63680 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..e3c13e17c5ad40541d89b6643a8fd779bf420f9a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/emission_factors.csv @@ -0,0 +1,11 @@ +source,factor_kg_co2e_per_unit,unit,scope +business_flights,0.158,km,3 +company_cars,0.16,km,1 +diesel_fleet,2.69,litre,1 +district_heating,0.0978,kWh,2 +heating_oil,2.73,litre,1 +natural_gas,0.186,kWh,1 +petrol_fleet,2.42,litre,1 +purchased_electricity,0.212,kWh,2 +rail_travel,0.0351,km,3 +waste_to_landfill,462.0,tonne,3 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..eee205d97f85282d8899d1652605653d3cded57a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Vessby Dairy Cooperative +- Reporting year: 2024 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..d3cbe2f8ed5d45d0bdc2782f96b898ca2ab455ca --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.48,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27467ea81a107dfaf4e6cb08adf0f9e4a00f2b97 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/instruction.md @@ -0,0 +1,21 @@ +# Emissions inventory: activity data + +You are compiling the 2024 greenhouse-gas inventory for Vessby Dairy Cooperative (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2024 only: leave out records whose `invoice_date` falls in another year. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..03ab5cb71c1c302769be8131d35b5cb5cd59d1c6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 76 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f31291d7aad79eb95d81d6ccc713f8481f07cd60 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/checks.json @@ -0,0 +1,93 @@ +[ + { + "path": "by_source.company_cars", + "type": "number", + "value": 28.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 62.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 5.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 75.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 47.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 24.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 2.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 237.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 5.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 2.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 245.53, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 141.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 104.52, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d2-t0076/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..4de4c8cdb73565a35bfce3126eb34924fa4298fc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/activity_data.csv @@ -0,0 +1,32 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2024-04-27,wood_pellets,19.41,tonne,INV-42221 +R002,warehouse,2024-04-11,petrol_fleet,2796.8,litre,INV-30377 +R003,depot,2024-01-14,diesel_fleet,4396.7,litre,INV-95068 +R004,depot,2024-11-21,diesel_fleet,6042.5,litre,INV-91411 +R005,depot,2024-04-01,rail_travel,67277,km,INV-29970 +R006,warehouse,2024-06-21,company_cars,25277,km,INV-88147 +R007,head_office,2024-12-20,company_cars,22440,km,INV-27146 +R008,depot,2024-05-15,diesel_fleet,3830.2,litre,INV-58334 +R009,depot,2024-08-22,heating_oil,3.504,m3,INV-26677 +R010,warehouse,2024-06-14,purchased_electricity,43.128,MWh,INV-30922 +R011,depot,2024-08-06,natural_gas,228.65,MWh,INV-70929 +R012,warehouse,2024-04-02,business_flights,79457,km,INV-83143 +R013,warehouse,2024-10-18,business_flights,33933,km,INV-31035 +R014,warehouse,2024-08-16,company_cars,10593,mile,INV-74204 +R015,depot,2025-01-06,heating_oil,2431.9,litre,INV-76509 +R016,depot,2024-02-21,heating_oil,3.713,m3,INV-48526 +R017,depot,2024-01-12,natural_gas,325323,kWh,INV-65844 +R018,depot,2024-03-18,petrol_fleet,3412.6,litre,INV-55771 +R019,depot,2024-11-12,wood_pellets,21190,kg,INV-47345 +R020,head_office,2024-07-22,business_flights,56662,km,INV-72051 +R021,warehouse,2024-03-23,purchased_electricity,93.974,MWh,INV-85388 +R022,warehouse,2024-01-06,rail_travel,60707,km,INV-49332 +R023,warehouse,2024-02-16,heating_oil,5.324,m3,INV-18346 +R024,warehouse,2025-01-14,diesel_fleet,8198.7,litre,INV-95733 +R025,depot,2024-08-24,purchased_electricity,64.176,MWh,INV-35648 +R026,head_office,2024-11-16,business_flights,24388,mile,INV-45962 +R027,depot,2024-02-19,diesel_fleet,7712.5,litre,INV-41023 +R028,warehouse,2024-10-22,heating_oil,6.006,m3,INV-87950 +R029,head_office,2023-11-05,heating_oil,4321.8,litre,INV-21016 +R030,warehouse,2024-10-15,purchased_electricity,71.026,MWh,INV-40315 +R031,depot,2024-11-27,petrol_fleet,1422.9,litre,INV-93896 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..3b1370d6c1587c4033379469055a142da8893f17 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.29,litre,outside scopes +business_flights,0.162,km,3 +company_cars,0.155,km,1 +diesel_fleet,2.53,litre,1 +district_heating,0.0942,kWh,2 +heating_oil,2.3,litre,1 +natural_gas,0.173,kWh,1 +petrol_fleet,2.19,litre,1 +purchased_electricity,0.224,kWh,2 +rail_travel,0.0319,km,3 +waste_to_landfill,438.0,tonne,3 +wood_pellets,1640.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..aff62215a242eb9ae2b7388a53a6e56f5fc2cc86 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Kestrel Joinery +- Reporting year: 2024 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..4af9c3850a433d99cb8dbcc2c1b2142595aaa5a7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.91,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..727083b9984acff6d0af3103ae1ee5598cfe8d81 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2024 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2024 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..670410e31fca76a226cbbf886c986d9317555bc7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "eval"] +isced_f = "0521" +family = "activity-data" +split = "eval" +seed = 10008 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..64702440926895b05c7f213f5cbe44e96a7a929a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/checks.json @@ -0,0 +1,148 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 33.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 10.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 55.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 42.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 95.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 16.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 61.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 4.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.wood_pellets", + "type": "number", + "value": 66.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 220.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 61.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 37.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 319.85, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 195.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 19.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 105.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 66.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "natural_gas", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 69.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 19.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 11.9, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0008/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..0696210af291e06a8d9b1a7fe5f6d0333a0f9e87 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/activity_data.csv @@ -0,0 +1,31 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,depot,2023-04-21,rail_travel,12018,km,INV-56280 +R002,workshop,2023-10-25,purchased_electricity,140518,kWh,INV-65339 +R003,depot,2023-12-23,wood_pellets,44.05,tonne,INV-58053 +R004,depot,2023-03-03,waste_to_landfill,17769,kg,INV-89335 +R005,depot,2023-03-21,business_flights,242286,km,INV-94575 +R006,depot,2023-02-26,purchased_electricity,210.048,MWh,INV-19256 +R007,depot,2022-11-08,diesel_fleet,1670.9,litre,INV-37906 +R008,workshop,2022-12-28,wood_pellets,34.74,tonne,INV-16618 +R009,workshop,2023-05-19,natural_gas,37591,kWh,INV-75869 +R010,depot,2023-05-06,biodiesel_b100,3.082,m3,INV-45923 +R011,head_office,2023-01-21,biodiesel_b100,3586.7,litre,INV-40695 +R012,depot,2023-10-18,rail_travel,22015,km,INV-83598 +R013,depot,2023-08-21,biodiesel_b100,3803.8,litre,INV-58421 +R014,depot,2023-05-13,district_heating,91.884,MWh,INV-45473 +R015,depot,2023-04-02,waste_to_landfill,16360,kg,INV-22291 +R016,workshop,2024-01-28,rail_travel,4649,km,INV-96474 +R017,depot,2023-09-21,diesel_fleet,19067.3,litre,INV-49754 +R018,depot,2023-01-23,purchased_electricity,137.766,MWh,INV-65826 +R019,workshop,2023-03-23,company_cars,28380,mile,INV-63425 +R020,depot,2023-11-18,rail_travel,22926,km,INV-34205 +R021,workshop,2023-07-13,district_heating,101684,kWh,INV-18840 +R022,workshop,2023-01-28,wood_pellets,51417,kg,INV-35493 +R023,depot,2023-10-19,business_flights,108728,km,INV-20384 +R024,depot,2023-05-17,natural_gas,35.561,MWh,INV-32052 +R025,workshop,2023-09-25,natural_gas,31.638,MWh,INV-52717 +R026,workshop,2023-09-21,company_cars,37786,mile,INV-40040 +R027,workshop,2023-01-05,natural_gas,26.254,MWh,INV-54660 +R028,workshop,2023-12-02,biodiesel_b100,2.185,m3,INV-19661 +R029,workshop,2023-09-24,waste_to_landfill,9.52,tonne,INV-19849 +R030,head_office,2023-06-16,diesel_fleet,19547.5,litre,INV-81305 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..ef36cd59b9a70a7e0eabd3cdcb69e7209b25c848 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.42,litre,outside scopes +business_flights,0.153,km,3 +company_cars,0.186,km,1 +diesel_fleet,2.83,litre,1 +district_heating,0.0996,kWh,2 +heating_oil,2.4,litre,1 +natural_gas,0.196,kWh,1 +petrol_fleet,2.25,litre,1 +purchased_electricity,0.234,kWh,2 +rail_travel,0.0356,km,3 +waste_to_landfill,458.0,tonne,3 +wood_pellets,1720.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..9d5b205f65632a275b464a71911fc5ecfb96c5a1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Brantholm Municipality +- Reporting year: 2023 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..cffa165d7eea9354eb917d3ca8bcf20bd2a8a239 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,11.0,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36fe5cdcfc78c82d615dcb6fabf34d0ab69a78ed --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2023 greenhouse-gas inventory for Brantholm Municipality (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2023 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a66d632720b78133a5ea05b4976080af1e41d01c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "eval"] +isced_f = "0521" +family = "activity-data" +split = "eval" +seed = 10020 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e11600e5bad03558b504cf1f9ecc2521a750e9cf --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/checks.json @@ -0,0 +1,155 @@ +[ + { + "path": "by_source.biodiesel_b100", + "type": "number", + "value": 30.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.business_flights", + "type": "number", + "value": 53.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 19.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 109.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 19.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 25.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 114.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 2.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 19.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.wood_pellets", + "type": "number", + "value": 164.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 154.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 133.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 75.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 364.04, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 222.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 55.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 85.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 194.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "purchased_electricity", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 42.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 36.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 20.8, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-e0020/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..e576fff8d05fcbfd0529157f37d3dcb9f7687d33 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/activity_data.csv @@ -0,0 +1,36 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,depot,2019-05-12,waste_to_landfill,1.5,tonne,INV-67908 +R002,warehouse,2019-10-02,district_heating,126205,kWh,INV-25035 +R003,warehouse,2019-02-23,diesel_fleet,1.575,m3,INV-29697 +R004,warehouse,2019-09-12,purchased_electricity,118377,kWh,INV-88298 +R005,head_office,2018-11-05,petrol_fleet,4260.4,litre,INV-22183 +R006,head_office,2019-02-24,rail_travel,90737,km,INV-23103 +R007,warehouse,2019-08-03,wood_pellets,39796,kg,INV-63194 +R008,head_office,2019-11-24,diesel_fleet,1706.7,litre,INV-44517 +R009,depot,2019-04-04,purchased_electricity,82.573,MWh,INV-35669 +R010,warehouse,2019-09-09,natural_gas,49.674,MWh,INV-68850 +R011,depot,2019-09-15,purchased_electricity,126.091,MWh,INV-20451 +R012,head_office,2019-08-19,biodiesel_b100,1707.2,litre,INV-63487 +R013,depot,2019-08-25,heating_oil,0.633,m3,INV-84643 +R014,head_office,2019-12-13,biodiesel_b100,827.2,litre,INV-53276 +R015,warehouse,2019-01-17,rail_travel,49339,km,INV-82042 +R016,head_office,2020-02-09,waste_to_landfill,7.63,tonne,INV-56656 +R017,head_office,2019-12-26,biodiesel_b100,1113.1,litre,INV-87894 +R018,head_office,2019-10-27,biodiesel_b100,794.2,litre,INV-62132 +R019,depot,2019-06-09,diesel_fleet,1492.3,litre,INV-74263 +R020,head_office,2019-05-13,petrol_fleet,611.8,litre,INV-80265 +R021,head_office,2018-11-26,natural_gas,45346,kWh,INV-67410 +R022,depot,2019-02-14,waste_to_landfill,2.53,tonne,INV-44662 +R023,depot,2019-06-19,petrol_fleet,962.9,litre,INV-12345 +R024,head_office,2019-09-14,diesel_fleet,1001.4,litre,INV-50484 +R025,head_office,2019-02-10,heating_oil,1205.3,litre,INV-14863 +R026,depot,2019-02-15,district_heating,131350,kWh,INV-58949 +R027,depot,2019-06-11,wood_pellets,40953,kg,INV-67816 +R028,warehouse,2019-03-21,purchased_electricity,100542,kWh,INV-75621 +R029,head_office,2019-11-17,natural_gas,29041,kWh,INV-95468 +R030,depot,2019-01-15,heating_oil,846.3,litre,INV-86901 +R031,depot,2019-08-20,waste_to_landfill,1865,kg,INV-29593 +R032,depot,2019-12-23,natural_gas,4287.906,m3,INV-27617 +R033,head_office,2019-04-25,district_heating,249.5,GJ,INV-38014 +R034,depot,2019-12-05,wood_pellets,32134,kg,INV-35073 +R035,warehouse,2019-09-02,heating_oil,1.113,m3,INV-96054 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..b9f08c11446f01567207cbabace348c2edebc61b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.65,litre,outside scopes +business_flights,0.147,km,3 +company_cars,0.155,km,1 +diesel_fleet,2.74,litre,1 +district_heating,0.106,kWh,2 +heating_oil,2.54,litre,1 +natural_gas,0.172,kWh,1 +petrol_fleet,2.46,litre,1 +purchased_electricity,0.22,kWh,2 +rail_travel,0.0343,km,3 +waste_to_landfill,470.0,tonne,3 +wood_pellets,1520.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..ca7335caca469f5668be83b5ede6ddbebbc78eac --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Harlow Fold Logistics +- Reporting year: 2019 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..cd334e257a0db8f7ea25845113171230c195b8a0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,11.12,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..591fa37bbe4e90bbf2ef486de78b55b1b746027b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2019 greenhouse-gas inventory for Harlow Fold Logistics (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2019 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bf62e3afea038f86d678767a3dc28d957cd6a2e7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 8 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ca3b6e0c70aa5e97a961caeb6e4a7cdf8a04bf83 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/checks.json @@ -0,0 +1,155 @@ +[ + { + "path": "by_source.biodiesel_b100", + "type": "number", + "value": 11.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 15.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 34.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 9.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 21.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 3.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 94.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 4.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 2.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.wood_pellets", + "type": "number", + "value": 171.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 51.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 128.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 7.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 187.38, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 81.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 27.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 78.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 183.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "purchased_electricity", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 27.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 68.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 4.0, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0008/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..8129403621ab0aeeed6b797ffbfbc9b8394be663 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/activity_data.csv @@ -0,0 +1,31 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,warehouse,2019-01-08,district_heating,118197,kWh,INV-54166 +R002,warehouse,2019-06-23,natural_gas,10433.347,m3,INV-36258 +R003,workshop,2019-04-18,business_flights,10796,mile,INV-22062 +R004,workshop,2019-04-23,rail_travel,39815,km,INV-33066 +R005,warehouse,2019-01-10,district_heating,206.821,MWh,INV-24024 +R006,warehouse,2019-08-23,purchased_electricity,93527,kWh,INV-28404 +R007,workshop,2019-06-16,business_flights,28436,mile,INV-24570 +R008,workshop,2019-02-02,heating_oil,2.502,m3,INV-51821 +R009,warehouse,2019-03-05,wood_pellets,29.15,tonne,INV-80404 +R010,warehouse,2019-06-01,natural_gas,12477.893,m3,INV-41977 +R011,warehouse,2019-01-14,heating_oil,2572.0,litre,INV-90083 +R012,warehouse,2020-01-26,district_heating,80423,kWh,INV-65082 +R013,warehouse,2018-12-09,diesel_fleet,4177.4,litre,INV-66737 +R014,warehouse,2019-07-26,rail_travel,55513,km,INV-29339 +R015,warehouse,2019-09-23,petrol_fleet,2172.4,litre,INV-83928 +R016,workshop,2019-04-13,petrol_fleet,1707.2,litre,INV-65545 +R017,workshop,2019-07-01,rail_travel,65019,km,INV-51182 +R018,warehouse,2019-05-08,business_flights,45627,km,INV-15662 +R019,workshop,2019-12-24,heating_oil,2.607,m3,INV-80563 +R020,warehouse,2019-12-07,wood_pellets,27.77,tonne,INV-47618 +R021,warehouse,2019-05-16,purchased_electricity,58.976,MWh,INV-41617 +R022,warehouse,2019-07-06,purchased_electricity,46.241,MWh,INV-25536 +R023,workshop,2019-04-08,purchased_electricity,90.048,MWh,INV-50338 +R024,workshop,2019-04-14,diesel_fleet,20732.1,litre,INV-39196 +R025,warehouse,2019-02-04,heating_oil,4.143,m3,INV-85377 +R026,workshop,2019-11-13,business_flights,19362,km,INV-53241 +R027,warehouse,2019-02-15,wood_pellets,34.16,tonne,INV-37224 +R028,warehouse,2019-09-01,diesel_fleet,18810.8,litre,INV-29993 +R029,warehouse,2019-11-13,natural_gas,168119,kWh,INV-39568 +R030,warehouse,2020-01-21,rail_travel,25903,km,INV-88139 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..0345a91f01bec14b39e3ae92a5306e651a249de2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.48,litre,outside scopes +business_flights,0.142,km,3 +company_cars,0.184,km,1 +diesel_fleet,2.76,litre,1 +district_heating,0.103,kWh,2 +heating_oil,2.79,litre,1 +natural_gas,0.176,kWh,1 +petrol_fleet,2.34,litre,1 +purchased_electricity,0.254,kWh,2 +rail_travel,0.038,km,3 +waste_to_landfill,464.0,tonne,3 +wood_pellets,1750.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..04eb28cc6b9265be1b9d6400bcc2f4b516d555ec --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Tarnwick Borough Council +- Reporting year: 2019 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..a19eca5a588154ab9d12ae073c12c05e8da51179 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.38,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c73820a0fea2814679d24fc23232354f0244be76 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2019 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2019 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..413999f92a6f81122c697fb492a39e3c5225bb2e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 20 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5d74164b44fde1c029256ff4e584b076e460686f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "by_source.business_flights", + "type": "number", + "value": 18.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 109.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 33.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 32.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 71.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 9.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 73.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 6.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.wood_pellets", + "type": "number", + "value": 159.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 222.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 106.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 24.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 353.77, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 239.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 114.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 159.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "diesel_fleet", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 62.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 30.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 6.9, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0020/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..9cf269e1c0c1afe1c5d484103488edd676837600 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/activity_data.csv @@ -0,0 +1,34 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,warehouse,2024-05-05,diesel_fleet,2805.2,litre,INV-40946 +R002,head_office,2024-10-24,business_flights,79537,km,INV-46584 +R003,head_office,2024-03-05,petrol_fleet,837.8,litre,INV-70731 +R004,head_office,2024-11-27,heating_oil,12.563,m3,INV-98415 +R005,warehouse,2025-02-19,biodiesel_b100,4493.2,litre,INV-97345 +R006,head_office,2024-07-10,wood_pellets,13685,kg,INV-72145 +R007,depot,2024-11-04,district_heating,35063,kWh,INV-67532 +R008,warehouse,2024-11-24,natural_gas,24246,kWh,INV-97509 +R009,warehouse,2024-04-26,biodiesel_b100,10751.7,litre,INV-75076 +R010,head_office,2024-05-14,diesel_fleet,2.719,m3,INV-74591 +R011,depot,2023-12-25,diesel_fleet,5.778,m3,INV-34767 +R012,depot,2024-04-14,biodiesel_b100,5981.4,litre,INV-51720 +R013,head_office,2024-05-10,waste_to_landfill,14.8,tonne,INV-19915 +R014,depot,2024-11-26,wood_pellets,20.81,tonne,INV-23235 +R015,warehouse,2024-02-01,natural_gas,3415.173,m3,INV-46737 +R016,warehouse,2024-11-07,district_heating,33.442,MWh,INV-85958 +R017,depot,2024-02-13,diesel_fleet,3427.3,litre,INV-88860 +R018,warehouse,2024-01-22,purchased_electricity,48.605,MWh,INV-13108 +R019,depot,2025-02-15,district_heating,17.935,MWh,INV-45276 +R020,head_office,2024-06-09,petrol_fleet,741.8,litre,INV-33127 +R021,head_office,2023-11-05,petrol_fleet,1024.5,litre,INV-59663 +R022,head_office,2024-02-13,petrol_fleet,642.9,litre,INV-44759 +R023,warehouse,2024-06-15,district_heating,35918,kWh,INV-77372 +R024,depot,2024-04-03,waste_to_landfill,21.96,tonne,INV-88723 +R025,head_office,2025-02-27,wood_pellets,13.53,tonne,INV-54578 +R026,depot,2024-10-27,waste_to_landfill,12340,kg,INV-50717 +R027,warehouse,2024-05-19,petrol_fleet,1466.0,litre,INV-49873 +R028,head_office,2024-12-10,diesel_fleet,4438.9,litre,INV-51435 +R029,warehouse,2024-11-20,purchased_electricity,35224,kWh,INV-66691 +R030,head_office,2024-04-01,business_flights,33324,mile,INV-27667 +R031,warehouse,2024-06-26,purchased_electricity,48028,kWh,INV-92286 +R032,head_office,2024-02-07,business_flights,26937,mile,INV-77360 +R033,head_office,2024-08-21,heating_oil,8484.9,litre,INV-14228 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..25efcca2900100a0c4338cc64d70bb8920894493 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.62,litre,outside scopes +business_flights,0.159,km,3 +company_cars,0.185,km,1 +diesel_fleet,2.54,litre,1 +district_heating,0.0929,kWh,2 +heating_oil,2.59,litre,1 +natural_gas,0.187,kWh,1 +petrol_fleet,2.28,litre,1 +purchased_electricity,0.255,kWh,2 +rail_travel,0.0333,km,3 +waste_to_landfill,433.0,tonne,3 +wood_pellets,1710.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..e4153133a30b50a665150ba099ab0fe9556a1d67 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Brantholm Municipality +- Reporting year: 2024 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..53fbbaec7fe11c877ee466a377503029cd8e76e3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,11.19,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1dc61d5a9adde25f2607f62442c57e9350816142 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2024 greenhouse-gas inventory for Brantholm Municipality (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2024 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3183a20d1e016f1498ba5d434c88faed65a4bff3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 32 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cba5142ac2c0cee2b97c8298026cef15faab580b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/checks.json @@ -0,0 +1,155 @@ +[ + { + "path": "by_source.biodiesel_b100", + "type": "number", + "value": 43.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.business_flights", + "type": "number", + "value": 28.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 34.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 9.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 54.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 11.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 8.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 33.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 21.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.wood_pellets", + "type": "number", + "value": 58.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 108.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 43.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 49.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 201.27, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 26.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 112.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 62.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 102.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "heating_oil", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 54.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 21.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 24.5, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0032/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..4310e25b04af543a819c695625639aeadab0c9cf --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/activity_data.csv @@ -0,0 +1,32 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,depot,2020-12-17,waste_to_landfill,15526,kg,INV-48573 +R002,depot,2021-11-09,business_flights,6259,mile,INV-23002 +R003,workshop,2021-04-08,diesel_fleet,16319.9,litre,INV-25443 +R004,depot,2020-11-15,biodiesel_b100,2115.6,litre,INV-40828 +R005,head_office,2021-09-21,heating_oil,3.922,m3,INV-59929 +R006,depot,2021-05-07,business_flights,15408,km,INV-21509 +R007,depot,2021-09-18,biodiesel_b100,10303.5,litre,INV-89338 +R008,workshop,2021-01-01,rail_travel,36630,km,INV-57519 +R009,head_office,2021-01-14,diesel_fleet,23002.7,litre,INV-43112 +R010,head_office,2021-12-12,waste_to_landfill,54744,kg,INV-47764 +R011,head_office,2021-01-21,purchased_electricity,174681,kWh,INV-60429 +R012,head_office,2021-09-26,rail_travel,81404,km,INV-13805 +R013,workshop,2021-04-25,business_flights,7003,mile,INV-43925 +R014,depot,2021-12-09,company_cars,29901,km,INV-72863 +R015,workshop,2020-11-14,business_flights,50538,mile,INV-29938 +R016,workshop,2021-09-14,heating_oil,5623.2,litre,INV-69873 +R017,workshop,2022-01-08,purchased_electricity,181.879,MWh,INV-30057 +R018,head_office,2021-03-22,business_flights,5876,mile,INV-28814 +R019,head_office,2022-01-28,waste_to_landfill,22.75,tonne,INV-83908 +R020,head_office,2021-12-02,rail_travel,62170,km,INV-71823 +R021,workshop,2021-08-19,company_cars,21836,mile,INV-55584 +R022,workshop,2021-12-05,district_heating,95.769,MWh,INV-34908 +R023,head_office,2021-03-06,district_heating,437.6,GJ,INV-76838 +R024,depot,2021-02-06,district_heating,101069,kWh,INV-16593 +R025,workshop,2021-11-02,purchased_electricity,80.008,MWh,INV-44733 +R026,head_office,2021-03-15,biodiesel_b100,3620.9,litre,INV-77094 +R027,depot,2021-05-21,waste_to_landfill,62.69,tonne,INV-92150 +R028,head_office,2021-02-20,company_cars,32025,km,INV-96887 +R029,depot,2021-05-13,purchased_electricity,99.943,MWh,INV-94657 +R030,depot,2021-10-10,district_heating,480.4,GJ,INV-34003 +R031,head_office,2021-02-12,purchased_electricity,194.192,MWh,INV-71897 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..f2aaa024c97591f1bd4ca2bfd3141e5bde71da22 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.29,litre,outside scopes +business_flights,0.144,km,3 +company_cars,0.171,km,1 +diesel_fleet,2.8,litre,1 +district_heating,0.0923,kWh,2 +heating_oil,2.34,litre,1 +natural_gas,0.185,kWh,1 +petrol_fleet,2.11,litre,1 +purchased_electricity,0.256,kWh,2 +rail_travel,0.0364,km,3 +waste_to_landfill,409.0,tonne,3 +wood_pellets,1780.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..e9be5a0440bb0046ceeeccd73eb95a1ad7805504 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Brantholm Municipality +- Reporting year: 2021 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..fa3a35248af90516937236e781f52e3693793d8b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.65,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c030ff488499d5e10e7e01898039691083da4c97 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2021 greenhouse-gas inventory for Brantholm Municipality (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2021 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d1f600d91d0eb796ad3965e6ca015a225ba3d79 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 44 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..7e7115b4480623738f7b1eceaa828558691302d6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/checks.json @@ -0,0 +1,148 @@ +[ + { + "path": "by_source.biodiesel_b100", + "type": "number", + "value": 31.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.business_flights", + "type": "number", + "value": 6.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 16.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 110.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 41.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 22.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 140.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 6.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 48.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 149.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 182.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 61.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 392.49, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 81.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 213.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 97.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 31.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "purchased_electricity", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 38.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 46.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 15.6, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0044/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..a99ff6aeec0e452f80e940ff0fab20aa3c1c3294 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/activity_data.csv @@ -0,0 +1,33 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,head_office,2019-02-19,waste_to_landfill,21041,kg,INV-58436 +R002,depot,2019-09-08,waste_to_landfill,21764,kg,INV-15308 +R003,workshop,2019-04-12,district_heating,114625,kWh,INV-63612 +R004,workshop,2019-09-13,purchased_electricity,113.743,MWh,INV-39833 +R005,head_office,2019-10-14,wood_pellets,22.74,tonne,INV-29376 +R006,workshop,2018-11-24,biodiesel_b100,1.089,m3,INV-70761 +R007,depot,2019-09-04,business_flights,72055,km,INV-69728 +R008,workshop,2019-10-15,wood_pellets,38.98,tonne,INV-45840 +R009,workshop,2019-12-27,district_heating,187.3,GJ,INV-54987 +R010,head_office,2019-06-10,district_heating,317.3,GJ,INV-20204 +R011,depot,2019-11-13,diesel_fleet,6.247,m3,INV-12229 +R012,head_office,2019-08-22,purchased_electricity,130752,kWh,INV-34872 +R013,head_office,2019-08-06,rail_travel,13729,km,INV-26081 +R014,head_office,2019-01-13,waste_to_landfill,22.93,tonne,INV-14404 +R015,depot,2019-06-01,rail_travel,28833,km,INV-92295 +R016,head_office,2019-12-22,waste_to_landfill,10.25,tonne,INV-73528 +R017,depot,2019-03-14,wood_pellets,20227,kg,INV-95199 +R018,workshop,2019-06-01,natural_gas,322584,kWh,INV-64567 +R019,head_office,2019-06-17,diesel_fleet,11765.9,litre,INV-80827 +R020,head_office,2019-08-17,diesel_fleet,9269.0,litre,INV-38674 +R021,depot,2020-02-03,rail_travel,5611,km,INV-81354 +R022,head_office,2019-10-24,natural_gas,148.674,MWh,INV-99086 +R023,workshop,2019-01-23,purchased_electricity,131532,kWh,INV-78291 +R024,depot,2018-11-22,district_heating,50.871,MWh,INV-28131 +R025,workshop,2019-08-24,purchased_electricity,125.11,MWh,INV-33066 +R026,workshop,2019-06-04,company_cars,137375,km,INV-34871 +R027,workshop,2019-05-27,biodiesel_b100,9.829,m3,INV-16948 +R028,head_office,2019-10-15,rail_travel,12213,km,INV-37922 +R029,depot,2019-03-13,business_flights,68169,mile,INV-19777 +R030,depot,2018-11-19,company_cars,8748,mile,INV-94512 +R031,workshop,2019-10-08,biodiesel_b100,7.448,m3,INV-91116 +R032,workshop,2019-11-07,company_cars,82719,km,INV-23509 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..64c3076efb760151f67cd3bcc4982f459401a09b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.59,litre,outside scopes +business_flights,0.171,km,3 +company_cars,0.18,km,1 +diesel_fleet,2.43,litre,1 +district_heating,0.106,kWh,2 +heating_oil,2.42,litre,1 +natural_gas,0.167,kWh,1 +petrol_fleet,2.09,litre,1 +purchased_electricity,0.252,kWh,2 +rail_travel,0.0316,km,3 +waste_to_landfill,428.0,tonne,3 +wood_pellets,1580.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..cb6be5820538da8085b54528dea94d925baa4f80 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Ostervik Bakery Group +- Reporting year: 2019 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..cf541575e6e0d9b406a2ce6c35ce7c7821644249 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.74,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47e9c7e8b35cc9f6cba41e7c28b019ffafad956c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2019 greenhouse-gas inventory for Ostervik Bakery Group (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2019 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..952d63493b951ce4e780a7ab452f91c00724271c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 56 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..da17b25a2c2d2b4ca35561aa39cf5913cb67496f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/checks.json @@ -0,0 +1,155 @@ +[ + { + "path": "by_source.biodiesel_b100", + "type": "number", + "value": 44.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.business_flights", + "type": "number", + "value": 31.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.company_cars", + "type": "number", + "value": 39.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 66.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 27.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 78.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 126.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 1.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 32.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.wood_pellets", + "type": "number", + "value": 129.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 184.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 153.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 65.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 403.24, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 56.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.head_office", + "type": "number", + "value": 142.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 204.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 174.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "purchased_electricity", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 45.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 38.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 16.2, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0056/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..067f197f178ffb8e432fcd05cfc27bd3eb4d62e1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/activity_data.csv @@ -0,0 +1,33 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,warehouse,2019-10-17,heating_oil,7437.1,litre,INV-86374 +R002,warehouse,2019-06-06,petrol_fleet,2607.9,litre,INV-89045 +R003,warehouse,2019-08-07,biodiesel_b100,3185.9,litre,INV-42780 +R004,warehouse,2019-04-19,biodiesel_b100,4.171,m3,INV-26386 +R005,warehouse,2020-01-21,heating_oil,5.352,m3,INV-40059 +R006,workshop,2018-11-26,rail_travel,24240,km,INV-84971 +R007,workshop,2019-09-06,rail_travel,23372,km,INV-50997 +R008,workshop,2019-05-01,district_heating,85017,kWh,INV-65413 +R009,workshop,2019-11-26,business_flights,67652,km,INV-86199 +R010,warehouse,2020-02-22,district_heating,73.606,MWh,INV-43049 +R011,workshop,2019-06-25,heating_oil,4.298,m3,INV-50091 +R012,workshop,2019-02-15,biodiesel_b100,2.838,m3,INV-85978 +R013,warehouse,2019-01-04,purchased_electricity,417571,kWh,INV-20733 +R014,workshop,2019-11-07,petrol_fleet,5644.1,litre,INV-53288 +R015,warehouse,2019-11-25,diesel_fleet,6753.6,litre,INV-85860 +R016,warehouse,2019-01-21,petrol_fleet,4352.1,litre,INV-12832 +R017,workshop,2019-01-07,biodiesel_b100,3642.7,litre,INV-21058 +R018,workshop,2019-12-21,heating_oil,3.951,m3,INV-93827 +R019,workshop,2019-03-27,waste_to_landfill,36.75,tonne,INV-33361 +R020,warehouse,2019-08-07,district_heating,117695,kWh,INV-92950 +R021,warehouse,2019-07-27,rail_travel,37862,km,INV-19105 +R022,workshop,2019-03-12,purchased_electricity,391894,kWh,INV-65744 +R023,warehouse,2019-11-21,diesel_fleet,15638.2,litre,INV-10006 +R024,workshop,2019-11-15,business_flights,117698,km,INV-92186 +R025,warehouse,2019-12-01,district_heating,311.8,GJ,INV-60472 +R026,warehouse,2019-03-20,business_flights,103838,km,INV-64517 +R027,warehouse,2019-10-18,rail_travel,22408,km,INV-84144 +R028,workshop,2019-01-13,district_heating,64.865,MWh,INV-86267 +R029,warehouse,2020-01-22,district_heating,78.347,MWh,INV-71029 +R030,workshop,2019-02-26,waste_to_landfill,26740,kg,INV-68537 +R031,warehouse,2020-02-09,diesel_fleet,9701.1,litre,INV-17096 +R032,warehouse,2019-09-13,rail_travel,40678,km,INV-41002 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..49fc6c1d40d67d199cf5c66f682949bf66d80008 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.25,litre,outside scopes +business_flights,0.169,km,3 +company_cars,0.176,km,1 +diesel_fleet,2.91,litre,1 +district_heating,0.0991,kWh,2 +heating_oil,2.51,litre,1 +natural_gas,0.201,kWh,1 +petrol_fleet,2.53,litre,1 +purchased_electricity,0.248,kWh,2 +rail_travel,0.0366,km,3 +waste_to_landfill,429.0,tonne,3 +wood_pellets,1730.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..04eb28cc6b9265be1b9d6400bcc2f4b516d555ec --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Tarnwick Borough Council +- Reporting year: 2019 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..323596bf0a8177ce3792767e5587bff9dc025f8f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,11.2,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c73820a0fea2814679d24fc23232354f0244be76 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2019 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2019 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd3a0896a3ec2c7b75c4076df90df9fd7ca2bb83 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 68 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f78362833545027f40b7ab5f4caf04e816e5ccc5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/checks.json @@ -0,0 +1,141 @@ +[ + { + "path": "by_source.biodiesel_b100", + "type": "number", + "value": 31.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.business_flights", + "type": "number", + "value": 48.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 65.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 35.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.heating_oil", + "type": "number", + "value": 39.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 31.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 200.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 4.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 27.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 136.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 235.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 80.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 452.93, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 246.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 206.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 31.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "purchased_electricity", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 30.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 52.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 17.8, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0068/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/activity_data.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/activity_data.csv new file mode 100644 index 0000000000000000000000000000000000000000..08026cd72f326e7da5430b3042e57657f3182bc3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/activity_data.csv @@ -0,0 +1,34 @@ +record_id,site,invoice_date,source,quantity,unit,supplier_ref +R001,depot,2022-08-23,diesel_fleet,15.171,m3,INV-81512 +R002,depot,2022-12-26,district_heating,128.1,GJ,INV-97289 +R003,workshop,2022-08-09,petrol_fleet,3185.0,litre,INV-32862 +R004,workshop,2022-10-15,district_heating,40349,kWh,INV-79237 +R005,warehouse,2022-12-25,natural_gas,69.134,MWh,INV-27381 +R006,warehouse,2022-08-13,wood_pellets,8383,kg,INV-12074 +R007,workshop,2022-12-18,petrol_fleet,2687.1,litre,INV-69711 +R008,depot,2022-01-08,business_flights,105561,km,INV-68429 +R009,warehouse,2022-06-28,biodiesel_b100,2266.6,litre,INV-67143 +R010,warehouse,2022-02-26,natural_gas,35.77,MWh,INV-15737 +R011,workshop,2022-04-27,purchased_electricity,80.955,MWh,INV-29426 +R012,workshop,2022-03-12,wood_pellets,6936,kg,INV-40411 +R013,workshop,2022-02-04,district_heating,33927,kWh,INV-72302 +R014,warehouse,2022-02-17,rail_travel,40607,km,INV-67724 +R015,workshop,2022-10-10,wood_pellets,17457,kg,INV-48400 +R016,depot,2022-07-19,petrol_fleet,3084.4,litre,INV-31946 +R017,warehouse,2023-01-06,purchased_electricity,101.211,MWh,INV-11780 +R018,warehouse,2022-09-20,biodiesel_b100,2029.1,litre,INV-38505 +R019,workshop,2021-11-13,natural_gas,42376,kWh,INV-88445 +R020,depot,2022-05-22,business_flights,68700,km,INV-70361 +R021,warehouse,2022-01-04,natural_gas,5473.908,m3,INV-18319 +R022,workshop,2022-03-06,waste_to_landfill,21.41,tonne,INV-67865 +R023,warehouse,2022-11-17,rail_travel,24812,km,INV-19780 +R024,warehouse,2023-01-20,waste_to_landfill,22.13,tonne,INV-40824 +R025,depot,2022-12-24,rail_travel,24707,km,INV-55350 +R026,workshop,2022-11-22,waste_to_landfill,18.64,tonne,INV-43768 +R027,workshop,2023-02-08,diesel_fleet,8848.6,litre,INV-79954 +R028,depot,2022-06-28,natural_gas,61.627,MWh,INV-17961 +R029,warehouse,2023-01-03,diesel_fleet,1583.8,litre,INV-32126 +R030,warehouse,2022-05-01,diesel_fleet,18442.7,litre,INV-80809 +R031,depot,2022-11-04,purchased_electricity,51600,kWh,INV-79993 +R032,workshop,2022-02-02,rail_travel,29337,km,INV-73786 +R033,depot,2022-10-01,business_flights,55801,mile,INV-44550 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/emission_factors.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/emission_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..d64ff5cc827b57ffabafde0599c0630cb2720b92 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/emission_factors.csv @@ -0,0 +1,13 @@ +source,factor_kg_co2e_per_unit,unit,scope +biodiesel_b100,2.28,litre,outside scopes +business_flights,0.16,km,3 +company_cars,0.176,km,1 +diesel_fleet,2.79,litre,1 +district_heating,0.0934,kWh,2 +heating_oil,2.31,litre,1 +natural_gas,0.19,kWh,1 +petrol_fleet,2.36,litre,1 +purchased_electricity,0.214,kWh,2 +rail_travel,0.0315,km,3 +waste_to_landfill,414.0,tonne,3 +wood_pellets,1800.0,tonne,outside scopes diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/inventory_boundary.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/inventory_boundary.md new file mode 100644 index 0000000000000000000000000000000000000000..786e51877ed083c50148fa82b90a6e436383d637 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/inventory_boundary.md @@ -0,0 +1,5 @@ +# Inventory boundary + +- Organisation: Vessby Dairy Cooperative +- Reporting year: 2022 (calendar year, by invoice date) +- Reported: scopes 1, 2 and 3 in tonnes CO2e diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/unit_conversions.csv b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/unit_conversions.csv new file mode 100644 index 0000000000000000000000000000000000000000..e3e9c4d6a6086a19d092b2ffa40da8ef11b3281c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/environment/workdir/unit_conversions.csv @@ -0,0 +1,9 @@ +from_unit,to_unit,multiply_by,applies_to +MWh,kWh,1000,all +GJ,kWh,277.78,all +m3,kWh,10.96,natural_gas +m3,litre,1000,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 +mile,km,1.609344,all +kg,tonne,0.001,all +therm,kWh,29.3071,all +gallon_uk,litre,4.54609,diesel_fleet;petrol_fleet;heating_oil;biodiesel_b100 diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/instruction.md b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..152e2140741bf1bf90c8131b71a7e73b5cc6d578 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/instruction.md @@ -0,0 +1,24 @@ +# Emissions inventory: activity data + +You are compiling the 2022 greenhouse-gas inventory for Vessby Dairy Cooperative (a synthetic organisation). + +- `activity_data.csv`: the activity records (fuel, energy, travel and waste), in whatever unit the supplier used. +- `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. +- `inventory_boundary.md`: the organisation and the reporting year. +- `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. + +The inventory covers the calendar year 2022 only: leave out records whose `invoice_date` falls in another year. Sources classed `outside scopes` in the factor table (biogenic CO2) are reported separately: work out their emissions and list them in `by_source`, but keep them out of `by_scope`, `by_site`, `total_t_co2e`, `scope_share_percent` and `largest_source`. + +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). + +Write `answer.json` in this folder, a JSON object with: + +- `by_source`: an object keyed by source, tonnes CO2e, 2 decimals. Include only sources that have records in the reporting year. +- `by_scope`: an object with keys `scope_1`, `scope_2` and `scope_3`, tonnes CO2e, 2 decimals. +- `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 2 decimals. +- `by_site`: an object keyed by site, tonnes CO2e of scopes 1 to 3 together, 2 decimals. +- `outside_scopes_t_co2e`: tonnes CO2e of the sources classed `outside scopes`, 2 decimals. +- `scope_share_percent`: an object with keys `scope_1`, `scope_2` and `scope_3`: each scope's share of `total_t_co2e` in percent, 1 decimal. +- `largest_source`: the source in scopes 1 to 3 with the largest emissions. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/task.toml b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ffe420500f9a771a40e2aa7a8f0963cf8fb179ed --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "activity-data", "isced-0521", "train"] +isced_f = "0521" +family = "activity-data" +split = "train" +seed = 80 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..db7ee222cdaf33f89ed251c3ae4bb29518283d08 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/checks.json @@ -0,0 +1,155 @@ +[ + { + "path": "by_source.biodiesel_b100", + "type": "number", + "value": 9.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.business_flights", + "type": "number", + "value": 42.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.diesel_fleet", + "type": "number", + "value": 93.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.district_heating", + "type": "number", + "value": 10.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.natural_gas", + "type": "number", + "value": 43.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.petrol_fleet", + "type": "number", + "value": 21.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.purchased_electricity", + "type": "number", + "value": 28.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.rail_travel", + "type": "number", + "value": 3.76, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.waste_to_landfill", + "type": "number", + "value": 16.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_source.wood_pellets", + "type": "number", + "value": 59.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_1", + "type": "number", + "value": 157.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_2", + "type": "number", + "value": 38.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_scope.scope_3", + "type": "number", + "value": 62.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 259.18, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "by_site.depot", + "type": "number", + "value": 118.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.warehouse", + "type": "number", + "value": 84.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site.workshop", + "type": "number", + "value": 55.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "outside_scopes_t_co2e", + "type": "number", + "value": 68.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "diesel_fleet", + "weight": 2 + }, + { + "path": "scope_share_percent.scope_1", + "type": "number", + "value": 60.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_2", + "type": "number", + "value": 14.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "scope_share_percent.scope_3", + "type": "number", + "value": 24.2, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-activity-data-d3-t0080/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..d758a0106aafad8592eaa65ba4a3174d6ea59eb1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2019 electricity return + +- Electricity emission factor: 0.353 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..a91373431c69bd0db44245065c6c5280f1eb8ab6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/environment/workdir/meter_readings.csv @@ -0,0 +1,41 @@ +meter_id,site,month,consumption,unit,invoice_ref +M58,workshop,2019-12,29463,kWh,E251787 +M58,workshop,2019-06,20343,kWh,E913956 +M09,depot,2019-01,17729,kWh,E173839 +M58,workshop,2019-03,22574,kWh,E559363 +M58,workshop,2019-07,21132,kWh,E990875 +M58,workshop,2019-04,23387,kWh,E811260 +M09,depot,2019-07,15720,kWh,E654187 +M52,workshop,2019-09,28008,kWh,E432691 +M09,depot,2019-02,16994,kWh,E380881 +M09,depot,2019-03,18234,kWh,E136917 +M58,workshop,2019-01,26897,kWh,E231716 +M58,workshop,2019-05,21629,kWh,E655240 +M09,depot,2019-11,17489,kWh,E314795 +M09,depot,2019-01,17729,kWh,E173839 +M58,workshop,2019-11,25414,kWh,E549372 +M52,workshop,2019-06,24845,kWh,E462405 +M58,workshop,2019-11,25414,kWh,E549372 +M09,depot,2019-04,14917,kWh,E159852 +M52,workshop,2019-05,27038,kWh,E633202 +M09,depot,2019-06,14908,kWh,E175022 +M09,depot,2019-10,18795,kWh,E227094 +M52,workshop,2019-11,30944,kWh,E233194 +M09,depot,2019-12,17775,kWh,E747138 +M09,depot,2019-05,15541,kWh,E970927 +M09,depot,2019-08,16503,kWh,E436858 +M58,workshop,2019-10,21908,kWh,E247445 +M52,workshop,2019-04,30040,kWh,E108083 +M52,workshop,2019-07,26162,kWh,E777982 +M58,workshop,2019-08,21419,kWh,E557459 +M52,workshop,2019-02,32326,kWh,E961254 +M58,workshop,2019-09,23663,kWh,E305590 +M52,workshop,2019-08,26624,kWh,E372541 +M58,workshop,2019-01,26897,kWh,E231716 +M52,workshop,2019-12,35529,kWh,E280255 +M58,workshop,2019-09,23663,kWh,E305590 +M52,workshop,2019-03,28649,kWh,E654676 +M52,workshop,2019-01,32239,kWh,E687140 +M58,workshop,2019-02,26237,kWh,E313785 +M09,depot,2019-09,16241,kWh,E945372 +M52,workshop,2019-10,28779,kWh,E583344 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3afef515f78ecdd88ea18fbf30805b0abfdcd86a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2019 monthly electricity consumption export for the meters of Ostervik Bakery Group (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e4628d73c74fd1a086b11e7da11c80cfd9aad1a0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "eval"] +isced_f = "0521" +family = "data-quality" +split = "eval" +seed = 10001 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2cdd760eae7c132568ed7a47be81155bc61d72e0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M09.annual_kwh", + "type": "number", + "value": 200846.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M09.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M52.annual_kwh", + "type": "number", + "value": 351183.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M52.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M58.annual_kwh", + "type": "number", + "value": 284066.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M58.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 836095.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 295.14, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0001/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..095508762cf1719c571f926c875e25e488031703 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2019 electricity return + +- Electricity emission factor: 0.443 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..9035127dbb63501c3ccb776fd02bfcd616a75c21 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/environment/workdir/meter_readings.csv @@ -0,0 +1,44 @@ +meter_id,site,month,consumption,unit,invoice_ref +M33,head_office,2019-07,33971,kWh,E481699 +M53,workshop,2019-11,33890,kWh,E737824 +M34,workshop,2019-06,3556,kWh,E257027 +M53,workshop,2019-06,24786,kWh,E536900 +M53,workshop,2019-04,29286,kWh,E504481 +M34,workshop,2019-12,5447,kWh,E899512 +M34,workshop,2019-09,4219,kWh,E122470 +M33,head_office,2019-12,43209,kWh,E709300 +M33,head_office,2019-01,36951,kWh,E822890 +M34,workshop,2019-05,4258,kWh,E504613 +M33,head_office,2019-05,34268,kWh,E266957 +M33,head_office,2019-08,33305,kWh,E850987 +M34,workshop,2019-03,4307,kWh,E702494 +M53,workshop,2019-12,37122,kWh,E995053 +M34,workshop,2019-08,4155,kWh,E738782 +M34,workshop,2019-04,3873,kWh,E774031 +M34,workshop,2019-02,4956,kWh,E939345 +M34,workshop,2019-07,3832,kWh,E391891 +M53,workshop,2019-03,29858,kWh,E192463 +M33,head_office,2019-06,32445,kWh,E341250 +M33,head_office,2019-03,35426,kWh,E991777 +M33,head_office,2019-04,34368,kWh,E626083 +M53,workshop,2019-02,29392,kWh,E756332 +M53,workshop,2019-01,33760,kWh,E403575 +M33,head_office,2019-10,36821,kWh,E134615 +M53,workshop,2019-09,30973,kWh,E869086 +M33,head_office,2019-05,34268,kWh,E266957 +M53,workshop,2019-07,25846,kWh,E419185 +M53,workshop,2019-05,30610,kWh,E971757 +M34,workshop,2019-10,4108,kWh,E615059 +M34,workshop,2019-04,3873,kWh,E774031 +M34,workshop,2019-01,5010,kWh,E954316 +M33,head_office,2019-09,36743,kWh,E570918 +M34,workshop,2019-03,4307,kWh,E702494 +M53,workshop,2019-01,33760,kWh,E403575 +M53,workshop,2019-03,29858,kWh,E192463 +M53,workshop,2019-10,32982,kWh,E765812 +M34,workshop,2019-08,4155,kWh,E738782 +M53,workshop,2019-08,31326,kWh,E110140 +M33,head_office,2019-02,41636,kWh,E979445 +M53,workshop,2019-09,30973,kWh,E869086 +M33,head_office,2019-11,35451,kWh,E334019 +M34,workshop,2019-11,4290,kWh,E848050 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..05b1ec75356995b5fd570dce949133853d153c82 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2019 monthly electricity consumption export for the meters of Kestrel Joinery (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b56e98f955fa2d11619cd8c6fc6318f848a77e1a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "eval"] +isced_f = "0521" +family = "data-quality" +split = "eval" +seed = 10013 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..627a3c15e727b2460d97efc055b612a9c85199ad --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M33.annual_kwh", + "type": "number", + "value": 434594.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M33.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M34.annual_kwh", + "type": "number", + "value": 52011.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M34.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M53.annual_kwh", + "type": "number", + "value": 369831.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M53.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 856436.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 379.4, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-e0013/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..72d6c16edf1d4d9cb1c5c8f2336f40185c5d922b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2022 electricity return + +- Electricity emission factor: 0.373 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..f969ece109b041775610d7457aaf46ba8b5155c3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/environment/workdir/meter_readings.csv @@ -0,0 +1,41 @@ +meter_id,site,month,consumption,unit,invoice_ref +M18,warehouse,2022-04,45494,kWh,E242979 +M18,warehouse,2022-09,41093,kWh,E370781 +M18,warehouse,2022-08,39468,kWh,E358309 +M18,warehouse,2022-01,52060,kWh,E359213 +M37,warehouse,2022-12,38052,kWh,E665653 +M37,warehouse,2022-01,37603,kWh,E898454 +M17,head_office,2022-12,19997,kWh,E750955 +M37,warehouse,2022-06,30156,kWh,E740308 +M37,warehouse,2022-07,27093,kWh,E558007 +M18,warehouse,2022-11,46468,kWh,E695607 +M17,head_office,2022-08,20604,kWh,E617371 +M17,head_office,2022-09,21055,kWh,E782813 +M37,warehouse,2022-05,33094,kWh,E363078 +M17,head_office,2022-05,20994,kWh,E266652 +M37,warehouse,2022-11,38347,kWh,E108934 +M37,warehouse,2022-04,32066,kWh,E175029 +M18,warehouse,2022-10,53337,kWh,E619574 +M18,warehouse,2022-03,46480,kWh,E651478 +M17,head_office,2022-01,27575,kWh,E485034 +M18,warehouse,2022-08,39468,kWh,E358309 +M18,warehouse,2022-02,50429,kWh,E539885 +M18,warehouse,2022-04,45494,kWh,E242979 +M18,warehouse,2022-06,35966,kWh,E812631 +M37,warehouse,2022-03,33217,kWh,E816254 +M17,head_office,2022-04,21221,kWh,E227173 +M17,head_office,2022-02,22419,kWh,E509233 +M37,warehouse,2022-09,30882,kWh,E264155 +M17,head_office,2022-06,19986,kWh,E970042 +M18,warehouse,2022-05,45605,kWh,E610104 +M17,head_office,2022-10,23725,kWh,E719115 +M18,warehouse,2022-12,49787,kWh,E445230 +M17,head_office,2022-08,20604,kWh,E617371 +M37,warehouse,2022-10,31726,kWh,E249621 +M18,warehouse,2022-07,40688,kWh,E131046 +M17,head_office,2022-11,22278,kWh,E354064 +M37,warehouse,2022-02,35045,kWh,E238353 +M18,warehouse,2022-06,35966,kWh,E812631 +M17,head_office,2022-03,24122,kWh,E233701 +M17,head_office,2022-07,20373,kWh,E631612 +M37,warehouse,2022-08,31503,kWh,E638372 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14ffcded355c291b386d2cb60e7f818d4cb5d442 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2022 monthly electricity consumption export for the meters of Brantholm Municipality (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5fa26a2652f3a3ebca44c9043da3f90ef8e0c1be --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 1 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b414426401d6ef46e152b473fbc5eaf05cc6ef5c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M17.annual_kwh", + "type": "number", + "value": 264349.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M17.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M18.annual_kwh", + "type": "number", + "value": 546875.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M18.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M37.annual_kwh", + "type": "number", + "value": 398784.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M37.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1210008.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 451.33, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0001/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..cb1f48b689a05b0f9fc1830ad8cbd7156345a8fd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2023 electricity return + +- Electricity emission factor: 0.087 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..ace43c50d259a77bcc882b7f7cbbac43e174d26a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/environment/workdir/meter_readings.csv @@ -0,0 +1,42 @@ +meter_id,site,month,consumption,unit,invoice_ref +M20,workshop,2023-09,18284,kWh,E975926 +M20,workshop,2023-11,19691,kWh,E289719 +M15,head_office,2023-04,9171,kWh,E800945 +M20,workshop,2023-08,15083,kWh,E789128 +M15,head_office,2023-07,8302,kWh,E737729 +M40,workshop,2023-02,41089,kWh,E776768 +M40,workshop,2023-09,33022,kWh,E253535 +M15,head_office,2023-08,8026,kWh,E553592 +M40,workshop,2023-03,38444,kWh,E921098 +M15,head_office,2023-10,10118,kWh,E462371 +M15,head_office,2023-06,8553,kWh,E814402 +M20,workshop,2023-04,17695,kWh,E671924 +M40,workshop,2023-11,33743,kWh,E706066 +M15,head_office,2023-05,8809,kWh,E211675 +M40,workshop,2023-04,34654,kWh,E389726 +M15,head_office,2023-01,10712,kWh,E716182 +M40,workshop,2023-03,38444,kWh,E921098 +M20,workshop,2023-02,20012,kWh,E981440 +M20,workshop,2023-06,16604,kWh,E172470 +M20,workshop,2023-05,16375,kWh,E757892 +M40,workshop,2023-05,31448,kWh,E488070 +M15,head_office,2023-03,8614,kWh,E604188 +M40,workshop,2023-10,38508,kWh,E183065 +M15,head_office,2023-08,8026,kWh,E553592 +M15,head_office,2023-11,11156,kWh,E298143 +M15,head_office,2023-12,10563,kWh,E785683 +M15,head_office,2023-02,9765,kWh,E227450 +M40,workshop,2023-08,32616,kWh,E396136 +M20,workshop,2023-07,16426,kWh,E292058 +M20,workshop,2023-12,22938,kWh,E159639 +M40,workshop,2023-07,28300,kWh,E943851 +M40,workshop,2023-12,38879,kWh,E213964 +M20,workshop,2023-10,19456,kWh,E145757 +M15,head_office,2023-02,9765,kWh,E227450 +M40,workshop,2023-01,39640,kWh,E659776 +M40,workshop,2023-06,30759,kWh,E235556 +M40,workshop,2023-01,39640,kWh,E659776 +M40,workshop,2023-04,34654,kWh,E389726 +M20,workshop,2023-01,19239,kWh,E607043 +M15,head_office,2023-09,8494,kWh,E889689 +M20,workshop,2023-03,18051,kWh,E132194 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f50735f046ff70cad0f74f8a71ee16d2b900cff6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2023 monthly electricity consumption export for the meters of Vessby Dairy Cooperative (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c4f63cb993f7eba553167a2a9654db10fef978ef --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 13 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..18c65eb6fec8e393cf8b2911ed24e656808b58ed --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M15.annual_kwh", + "type": "number", + "value": 112283.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M15.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M20.annual_kwh", + "type": "number", + "value": 219854.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M20.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M40.annual_kwh", + "type": "number", + "value": 421102.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M40.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 753239.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 65.53, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0013/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..a23e6da59ceb8a5faccc1091fd1d9ea803ab9e54 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2023 electricity return + +- Electricity emission factor: 0.093 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..acf0f7b1c10d755cbb0b14a4182335e687c3990a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/environment/workdir/meter_readings.csv @@ -0,0 +1,41 @@ +meter_id,site,month,consumption,unit,invoice_ref +M07,depot,2023-01,20355,kWh,E377622 +M21,depot,2023-02,31414,kWh,E233480 +M21,depot,2023-08,23611,kWh,E436118 +M11,workshop,2023-06,3497,kWh,E626043 +M11,workshop,2023-11,4516,kWh,E371605 +M21,depot,2023-02,31414,kWh,E233480 +M07,depot,2023-08,17258,kWh,E395179 +M11,workshop,2023-12,4728,kWh,E694361 +M21,depot,2023-06,26012,kWh,E625570 +M21,depot,2023-04,28485,kWh,E578643 +M07,depot,2023-07,13606,kWh,E389758 +M21,depot,2023-07,21926,kWh,E364115 +M07,depot,2023-03,17525,kWh,E935260 +M11,workshop,2023-04,4031,kWh,E583566 +M11,workshop,2023-10,4375,kWh,E797690 +M11,workshop,2023-06,3497,kWh,E626043 +M21,depot,2023-05,27436,kWh,E213447 +M07,depot,2023-10,15426,kWh,E618845 +M07,depot,2023-12,17765,kWh,E368333 +M21,depot,2023-12,28713,kWh,E800292 +M11,workshop,2023-03,4442,kWh,E654473 +M07,depot,2023-05,15964,kWh,E676385 +M21,depot,2023-01,33173,kWh,E792632 +M21,depot,2023-10,25618,kWh,E463339 +M07,depot,2023-11,18057,kWh,E361218 +M21,depot,2023-11,28384,kWh,E915962 +M11,workshop,2023-07,4132,kWh,E834159 +M11,workshop,2023-05,3792,kWh,E908391 +M11,workshop,2023-01,4629,kWh,E557778 +M11,workshop,2023-02,4715,kWh,E432888 +M21,depot,2023-03,28420,kWh,E171101 +M07,depot,2023-09,17219,kWh,E744340 +M21,depot,2023-09,27124,kWh,E697160 +M11,workshop,2023-08,4370,kWh,E549577 +M07,depot,2023-01,20355,kWh,E377622 +M07,depot,2023-04,16124,kWh,E774082 +M07,depot,2023-02,18512,kWh,E678705 +M21,depot,2023-03,28420,kWh,E171101 +M07,depot,2023-06,15815,kWh,E445826 +M11,workshop,2023-09,3886,kWh,E380217 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0b9a8165bd86bb7292a6283a148fa0c87a66ecd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2023 monthly electricity consumption export for the meters of Marrow Vale Housing (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..98dc3650d62100754c0e65d9c8515a4df2e166d0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 25 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c3993169db6b7f6da359a962cfc0ffd5365b2fc0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M07.annual_kwh", + "type": "number", + "value": 203626.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M07.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M11.annual_kwh", + "type": "number", + "value": 51113.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M11.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M21.annual_kwh", + "type": "number", + "value": 330316.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M21.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 585055.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 54.41, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0025/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..40478a6adb7fbfd45c9c171bf5ee97dda1d3cfd4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2021 electricity return + +- Electricity emission factor: 0.418 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..ec0e0596376c3cddfef39b26d0ca210eeeab1259 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/environment/workdir/meter_readings.csv @@ -0,0 +1,40 @@ +meter_id,site,month,consumption,unit,invoice_ref +M05,workshop,2021-05,14821,kWh,E511717 +M05,workshop,2021-03,15539,kWh,E819935 +M21,depot,2021-04,28354,kWh,E982065 +M21,depot,2021-10,28889,kWh,E174183 +M02,depot,2021-12,48324,kWh,E654914 +M21,depot,2021-05,26304,kWh,E696194 +M21,depot,2021-08,28811,kWh,E696904 +M21,depot,2021-07,25748,kWh,E289403 +M02,depot,2021-06,33941,kWh,E740368 +M02,depot,2021-07,33176,kWh,E875214 +M05,workshop,2021-04,14927,kWh,E967537 +M02,depot,2021-02,48034,kWh,E683819 +M02,depot,2021-04,39701,kWh,E689873 +M21,depot,2021-12,35089,kWh,E846103 +M02,depot,2021-05,34715,kWh,E375170 +M21,depot,2021-06,26583,kWh,E271119 +M02,depot,2021-09,42157,kWh,E431227 +M02,depot,2021-08,37737,kWh,E273349 +M21,depot,2021-05,26304,kWh,E696194 +M05,workshop,2021-10,15049,kWh,E421512 +M05,workshop,2021-09,15817,kWh,E424052 +M02,depot,2021-11,44448,kWh,E212076 +M21,depot,2021-01,33539,kWh,E553014 +M05,workshop,2021-06,13087,kWh,E880769 +M21,depot,2021-02,31984,kWh,E377931 +M21,depot,2021-09,32431,kWh,E486714 +M21,depot,2021-11,33360,kWh,E708341 +M05,workshop,2021-08,14923,kWh,E467873 +M05,workshop,2021-01,18719,kWh,E702900 +M02,depot,2021-10,40866,kWh,E664345 +M05,workshop,2021-07,12956,kWh,E892099 +M21,depot,2021-03,27086,kWh,E686040 +M05,workshop,2021-02,17828,kWh,E985586 +M02,depot,2021-01,54067,kWh,E463260 +M05,workshop,2021-12,17795,kWh,E869419 +M05,workshop,2021-11,19437,kWh,E491967 +M02,depot,2021-03,40197,kWh,E541466 +M21,depot,2021-08,28811,kWh,E696904 +M21,depot,2021-02,31984,kWh,E377931 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ee81e3422b1d63ceb29a456dfb14cc644a59331 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2021 monthly electricity consumption export for the meters of Kestrel Joinery (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f6f99d41b483af06127006579ad28258b7f69e87 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 37 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f7e3a8eedfd7e3fb137a8f0bce7bf7129e791edc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M02.annual_kwh", + "type": "number", + "value": 497363.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M02.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M05.annual_kwh", + "type": "number", + "value": 190898.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M05.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M21.annual_kwh", + "type": "number", + "value": 358178.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M21.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1046439.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 437.41, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0037/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..762b49d12efd813c862c1ba3db1ad2ab65cf3dc1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2023 electricity return + +- Electricity emission factor: 0.401 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..127f2121fa41a33ef852de715f16a042fd60a968 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/environment/workdir/meter_readings.csv @@ -0,0 +1,42 @@ +meter_id,site,month,consumption,unit,invoice_ref +M11,workshop,2023-09,45501,kWh,E689020 +M08,head_office,2023-08,15730,kWh,E883045 +M08,head_office,2023-02,17179,kWh,E783598 +M08,head_office,2023-09,14742,kWh,E746610 +M51,head_office,2023-06,13610,kWh,E495471 +M11,workshop,2023-02,48243,kWh,E661052 +M11,workshop,2023-11,48876,kWh,E537174 +M11,workshop,2023-08,42799,kWh,E841256 +M11,workshop,2023-06,44377,kWh,E309094 +M51,head_office,2023-03,15746,kWh,E988493 +M51,head_office,2023-02,18286,kWh,E171478 +M51,head_office,2023-06,13610,kWh,E495471 +M11,workshop,2023-07,39754,kWh,E309303 +M11,workshop,2023-04,47403,kWh,E778901 +M51,head_office,2023-08,14073,kWh,E115653 +M51,head_office,2023-11,17673,kWh,E693897 +M11,workshop,2023-07,39754,kWh,E309303 +M08,head_office,2023-08,15730,kWh,E883045 +M11,workshop,2023-03,44142,kWh,E876623 +M08,head_office,2023-03,18361,kWh,E356415 +M51,head_office,2023-07,12892,kWh,E826796 +M11,workshop,2023-05,43623,kWh,E331117 +M11,workshop,2023-10,48645,kWh,E430385 +M11,workshop,2023-01,53714,kWh,E589131 +M51,head_office,2023-05,14942,kWh,E498994 +M08,head_office,2023-12,18156,kWh,E177848 +M51,head_office,2023-04,16478,kWh,E861434 +M08,head_office,2023-05,15597,kWh,E358611 +M08,head_office,2023-04,15480,kWh,E735304 +M51,head_office,2023-01,17116,kWh,E558117 +M08,head_office,2023-01,18234,kWh,E665216 +M08,head_office,2023-09,14742,kWh,E746610 +M08,head_office,2023-11,19195,kWh,E331468 +M11,workshop,2023-12,48977,kWh,E144145 +M08,head_office,2023-07,13694,kWh,E421803 +M51,head_office,2023-09,14865,kWh,E256307 +M08,head_office,2023-10,16563,kWh,E919327 +M08,head_office,2023-04,15480,kWh,E735304 +M51,head_office,2023-10,15929,kWh,E721571 +M51,head_office,2023-12,16670,kWh,E616594 +M08,head_office,2023-06,13809,kWh,E699165 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7bdca00c7b36d39abf2c294f039035099c544fdc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2023 monthly electricity consumption export for the meters of Tarnwick Borough Council (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8cb0bf734cc72349d11c6f260b3380e5ff29cf5a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 49 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..006ef12e9c59c234fd314f7a46c7744ac6edbe3a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M08.annual_kwh", + "type": "number", + "value": 196740.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M08.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M11.annual_kwh", + "type": "number", + "value": 556054.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M11.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M51.annual_kwh", + "type": "number", + "value": 188280.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M51.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 941074.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 377.37, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0049/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..4cf6f1ba808b75979660c2917c799789f928e817 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2021 electricity return + +- Electricity emission factor: 0.220 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..ff8f38c556e4647ec5f3beb8472691550885fef1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/environment/workdir/meter_readings.csv @@ -0,0 +1,44 @@ +meter_id,site,month,consumption,unit,invoice_ref +M03,depot,2021-06,34355,kWh,E498828 +M56,warehouse,2021-01,24661,kWh,E268240 +M56,warehouse,2021-05,20504,kWh,E461881 +M18,warehouse,2021-12,28892,kWh,E678498 +M18,warehouse,2021-10,25700,kWh,E105543 +M18,warehouse,2021-03,24151,kWh,E644538 +M18,warehouse,2021-06,22032,kWh,E988914 +M03,depot,2021-12,43846,kWh,E394177 +M56,warehouse,2021-12,24275,kWh,E822186 +M03,depot,2021-02,45407,kWh,E818942 +M56,warehouse,2021-07,18062,kWh,E341753 +M18,warehouse,2021-09,26387,kWh,E107952 +M03,depot,2021-05,35378,kWh,E461437 +M18,warehouse,2021-05,21099,kWh,E732714 +M56,warehouse,2021-01,24661,kWh,E268240 +M03,depot,2021-03,38158,kWh,E114433 +M18,warehouse,2021-05,21099,kWh,E732714 +M56,warehouse,2021-12,24275,kWh,E822186 +M18,warehouse,2021-01,26629,kWh,E461394 +M03,depot,2021-09,38815,kWh,E954543 +M56,warehouse,2021-03,20870,kWh,E977217 +M56,warehouse,2021-03,20870,kWh,E977217 +M03,depot,2021-10,39450,kWh,E863393 +M56,warehouse,2021-02,20743,kWh,E287773 +M03,depot,2021-08,36627,kWh,E133348 +M56,warehouse,2021-11,21735,kWh,E269738 +M18,warehouse,2021-04,26883,kWh,E965414 +M56,warehouse,2021-09,19565,kWh,E619336 +M03,depot,2021-04,39337,kWh,E119114 +M03,depot,2021-05,35378,kWh,E461437 +M56,warehouse,2021-04,21471,kWh,E599031 +M56,warehouse,2021-10,20790,kWh,E491511 +M56,warehouse,2021-06,16552,kWh,E515885 +M18,warehouse,2021-11,26090,kWh,E497332 +M03,depot,2021-07,33299,kWh,E204609 +M18,warehouse,2021-11,26090,kWh,E497332 +M03,depot,2021-01,48288,kWh,E188250 +M18,warehouse,2021-08,22297,kWh,E398285 +M18,warehouse,2021-07,21721,kWh,E353326 +M18,warehouse,2021-03,24151,kWh,E644538 +M03,depot,2021-11,45781,kWh,E971180 +M18,warehouse,2021-02,25034,kWh,E366313 +M56,warehouse,2021-08,18397,kWh,E545755 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ee81e3422b1d63ceb29a456dfb14cc644a59331 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2021 monthly electricity consumption export for the meters of Kestrel Joinery (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c8be9bc55178041b0b87c0353891ec7089614a09 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 61 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ad503157e0c0f0c8945f8a59e1e12e024517d137 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M03.annual_kwh", + "type": "number", + "value": 478741.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M03.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M18.annual_kwh", + "type": "number", + "value": 296915.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M18.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M56.annual_kwh", + "type": "number", + "value": 247625.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M56.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1023281.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 225.12, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0061/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..212d5cf31cf2e9566b7b12182426b682cb0f4447 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/workdir/data_rules.md @@ -0,0 +1,6 @@ +# Data rules for the 2021 electricity return + +- Electricity emission factor: 0.317 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..f3b1d94e9fc009159eaca8cc50153434bd2a9972 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/environment/workdir/meter_readings.csv @@ -0,0 +1,42 @@ +meter_id,site,month,consumption,unit,invoice_ref +M36,head_office,2021-11,39689,kWh,E256723 +M15,head_office,2021-03,43011,kWh,E384190 +M15,head_office,2021-02,39852,kWh,E226494 +M06,depot,2021-01,33239,kWh,E289121 +M36,head_office,2021-08,30293,kWh,E781500 +M15,head_office,2021-06,36342,kWh,E799810 +M15,head_office,2021-04,38047,kWh,E152697 +M15,head_office,2021-12,45964,kWh,E464592 +M06,depot,2021-03,34413,kWh,E842341 +M15,head_office,2021-05,38372,kWh,E290863 +M36,head_office,2021-03,32916,kWh,E670034 +M06,depot,2021-07,26321,kWh,E100784 +M15,head_office,2021-07,33762,kWh,E134306 +M36,head_office,2021-02,35839,kWh,E980303 +M06,depot,2021-02,36396,kWh,E584824 +M36,head_office,2021-05,30872,kWh,E899042 +M15,head_office,2021-11,42156,kWh,E288050 +M06,depot,2021-11,33680,kWh,E513043 +M36,head_office,2021-05,30872,kWh,E899042 +M36,head_office,2021-12,41926,kWh,E425498 +M06,depot,2021-10,33178,kWh,E262900 +M06,depot,2021-06,27530,kWh,E777156 +M06,depot,2021-09,32858,kWh,E511383 +M06,depot,2021-05,29474,kWh,E711187 +M06,depot,2021-12,39975,kWh,E185432 +M36,head_office,2021-04,36312,kWh,E176421 +M15,head_office,2021-10,39055,kWh,E647864 +M15,head_office,2021-01,39649,kWh,E194769 +M06,depot,2021-01,33239,kWh,E289121 +M06,depot,2021-08,27100,kWh,E308337 +M15,head_office,2021-09,36292,kWh,E668814 +M36,head_office,2021-07,30725,kWh,E352171 +M36,head_office,2021-01,41103,kWh,E349140 +M36,head_office,2021-04,36312,kWh,E176421 +M06,depot,2021-06,27530,kWh,E777156 +M36,head_office,2021-11,39689,kWh,E256723 +M36,head_office,2021-10,36415,kWh,E742518 +M36,head_office,2021-09,34868,kWh,E122624 +M36,head_office,2021-06,27308,kWh,E550733 +M06,depot,2021-04,32934,kWh,E303194 +M15,head_office,2021-08,36077,kWh,E319759 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d040020b53e4ac64a5c66749f33bad715e75925 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/instruction.md @@ -0,0 +1,14 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2021 monthly electricity consumption export for the meters of Harlow Fold Logistics (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..65af5b2435226474ef66c60bd3b91bcc820fe330 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 73 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..796c2d1cd06c7bf94f08f0b48223b92280fcd784 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/checks.json @@ -0,0 +1,61 @@ +[ + { + "path": "meters.M06.annual_kwh", + "type": "number", + "value": 387098.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M06.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M15.annual_kwh", + "type": "number", + "value": 468579.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M15.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M36.annual_kwh", + "type": "number", + "value": 418266.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M36.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1273943.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 403.84, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d1-t0073/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..3208b9c165a87e3ad881d7ed53de38937f9ee40d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2021 electricity return + +- Electricity emission factor: 0.162 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..59c1d7f46c5dd0d59a3f796016d880f1a6c92c69 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/environment/workdir/meter_readings.csv @@ -0,0 +1,67 @@ +meter_id,site,month,consumption,unit,invoice_ref +M06,warehouse,2021-05,36637,kWh,E647023 +M05,depot,2021-05,20461,kWh,E257513 +M06,warehouse,2021-06,36689,kWh,E711808 +M37,warehouse,2021-06,35663,kWh,E708959 +M06,warehouse,2021-03,45634,kWh,E514878 +M32,depot,2021-09,15791,kWh,E229493 +M05,depot,2021-11,24454,kWh,E887588 +M32,depot,2021-11,15944,kWh,E973077 +M45,warehouse,2021-09,26173,kWh,E332481 +M45,warehouse,2021-05,23807,kWh,E757287 +M06,warehouse,2021-03,45634,kWh,E514878 +M06,warehouse,2021-12,47318,kWh,E397455 +M37,warehouse,2021-04,40513,kWh,E569115 +M45,warehouse,2021-03,23286,kWh,E669993 +M06,warehouse,2021-09,42678,kWh,E346063 +M05,depot,2021-06,18706,kWh,E429839 +M05,depot,2021-08,19140,kWh,E945847 +M45,warehouse,2021-01,25705,kWh,E421694 +M32,depot,2021-03,14428,kWh,E364715 +M45,warehouse,2021-06,21054,kWh,E167511 +M05,depot,2021-09,22916,kWh,E762694 +M05,depot,2021-02,26196,kWh,E302861 +M32,depot,2021-07,12459,kWh,E211517 +M06,warehouse,2021-12,47318,kWh,E397455 +M05,depot,2021-12,24104,kWh,E454410 +M06,warehouse,2021-10,40979,kWh,E165848 +M37,warehouse,2021-10,43422,kWh,E146776 +M05,depot,2021-04,20684,kWh,E395329 +M32,depot,2021-04,15126,kWh,E461509 +M32,depot,2021-12,18556,kWh,E789438 +M06,warehouse,2021-01,43921,kWh,E141564 +M37,warehouse,2021-03,45271,kWh,E932535 +M45,warehouse,2021-04,24010,kWh,E137485 +M45,warehouse,2021-07,21729,kWh,E829016 +M32,depot,2021-04,15126,kWh,E461509 +M45,warehouse,2021-04,24010,kWh,E137485 +M37,warehouse,2021-05,40754,kWh,E908911 +M32,depot,2021-08,13463,kWh,E907332 +M45,warehouse,2021-12,28103,kWh,E340917 +M06,warehouse,2021-04,35793,kWh,E473593 +M05,depot,2021-03,21208,kWh,E205388 +M45,warehouse,2021-10,26356,kWh,E130649 +M37,warehouse,2021-08,37759,kWh,E687656 +M32,depot,2021-10,15916,kWh,E442181 +M06,warehouse,2021-11,41109,kWh,E500242 +M06,warehouse,2021-07,34256,kWh,E657022 +M45,warehouse,2021-11,27602,kWh,E210638 +M05,depot,2021-10,22948,kWh,E933704 +M37,warehouse,2021-12,53874,kWh,E946135 +M37,warehouse,2021-02,51299,kWh,E544206 +M32,depot,2021-06,14429,kWh,E592859 +M32,depot,2021-12,18556,kWh,E789438 +M32,depot,2021-02,16337,kWh,E106586 +M32,depot,2021-01,19133,kWh,E591897 +M45,warehouse,2021-10,26356,kWh,E130649 +M37,warehouse,2021-01,53299,kWh,E176004 +M37,warehouse,2021-11,53698,kWh,E247061 +M37,warehouse,2021-10,43422,kWh,E146776 +M32,depot,2021-05,14699,kWh,E154912 +M05,depot,2021-01,24868,kWh,E392556 +M06,warehouse,2021-02,42351,kWh,E759427 +M05,depot,2021-07,20297,kWh,E387809 +M37,warehouse,2021-07,40393,kWh,E451556 +M45,warehouse,2021-08,20977,kWh,E919115 +M06,warehouse,2021-04,35793,kWh,E473593 +M06,warehouse,2021-08,39038,kWh,E351548 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5bcd7697cfb920520756626387e645bd8068205 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2021 monthly electricity consumption export for the meters of Lindqvist Castings (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0a3e828badaff8667f880b6de38c49baedaab1dc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "eval"] +isced_f = "0521" +family = "data-quality" +split = "eval" +seed = 10005 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f1d6645990499f94a9e20aa98cb9ff04ae9a6db0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M05.annual_kwh", + "type": "number", + "value": 265982.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M05.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M06.annual_kwh", + "type": "number", + "value": 486403.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M06.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M32.annual_kwh", + "type": "number", + "value": 186281.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M32.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M37.annual_kwh", + "type": "number", + "value": 536535.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M37.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M45.annual_kwh", + "type": "number", + "value": 293297.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M45.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1768499.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 286.5, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M37.2021-09", + "type": "number", + "value": 40590.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M45.2021-02", + "type": "number", + "value": 24495.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M37", + "M45" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0005/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..b28c9e107e8a294b055fa8ff9327f1557f2018fc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2021 electricity return + +- Electricity emission factor: 0.384 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..07413d443efb049cb7f8ca4796bb9ea3ee5398ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/environment/workdir/meter_readings.csv @@ -0,0 +1,69 @@ +meter_id,site,month,consumption,unit,invoice_ref +M01,warehouse,2021-10,28345,kWh,E340339 +M09,workshop,2021-04,30669,kWh,E580472 +M57,warehouse,2021-03,51276,kWh,E822226 +M09,workshop,2021-06,27816,kWh,E457402 +M01,warehouse,2021-07,25969,kWh,E545356 +M57,warehouse,2021-09,43041,kWh,E723788 +M49,workshop,2021-01,14652,kWh,E686620 +M01,warehouse,2021-11,29475,kWh,E710573 +M50,warehouse,2021-12,28275,kWh,E528209 +M50,warehouse,2021-11,28336,kWh,E686690 +M49,workshop,2021-06,9304,kWh,E718555 +M49,workshop,2021-10,12240,kWh,E928673 +M49,workshop,2021-05,10570,kWh,E347187 +M01,warehouse,2021-01,29817,kWh,E969853 +M57,warehouse,2021-05,43572,kWh,E154653 +M09,workshop,2021-10,30443,kWh,E532238 +M50,warehouse,2021-06,22405,kWh,E402354 +M01,warehouse,2021-03,27819,kWh,E639160 +M50,warehouse,2021-06,22405,kWh,E402354 +M01,warehouse,2021-07,25969,kWh,E545356 +M49,workshop,2021-11,13071,kWh,E205288 +M57,warehouse,2021-08,44736,kWh,E304764 +M50,warehouse,2021-05,23480,kWh,E701885 +M49,workshop,2021-02,12877,kWh,E299533 +M57,warehouse,2021-01,44792,kWh,E810029 +M01,warehouse,2021-09,27039,kWh,E113927 +M57,warehouse,2021-03,51276,kWh,E822226 +M09,workshop,2021-08,24580,kWh,E755717 +M09,workshop,2021-09,28452,kWh,E990954 +M09,workshop,2021-02,30732,kWh,E913803 +M57,warehouse,2021-11,46956,kWh,E580084 +M49,workshop,2021-12,13947,kWh,E285433 +M09,workshop,2021-05,25341,kWh,E950283 +M01,warehouse,2021-01,29817,kWh,E969853 +M01,warehouse,2021-12,31664,kWh,E232914 +M57,warehouse,2021-12,51937,kWh,E836187 +M50,warehouse,2021-07,24144,kWh,E558498 +M09,workshop,2021-11,34325,kWh,E303721 +M57,warehouse,2021-11,46956,kWh,E580084 +M57,warehouse,2021-02,45204,kWh,E472288 +M09,workshop,2021-01,32198,kWh,E297675 +M50,warehouse,2021-01,29822,kWh,E229080 +M57,warehouse,2021-06,43772,kWh,E876052 +M09,workshop,2021-10,30443,kWh,E532238 +M01,warehouse,2021-05,24397,kWh,E187718 +M09,workshop,2021-04,30669,kWh,E580472 +M50,warehouse,2021-09,24242,kWh,E700503 +M50,warehouse,2021-04,26667,kWh,E870867 +M49,workshop,2021-03,11212,kWh,E911972 +M49,workshop,2021-07,9467,kWh,E573682 +M49,workshop,2021-04,10851,kWh,E345175 +M50,warehouse,2021-02,26660,kWh,E895728 +M01,warehouse,2021-04,25188,kWh,E815089 +M57,warehouse,2021-04,46453,kWh,E374258 +M09,workshop,2021-07,23905,kWh,E790668 +M01,warehouse,2021-02,33090,kWh,E318684 +M57,warehouse,2021-07,41299,kWh,E844074 +M01,warehouse,2021-06,22850,kWh,E669283 +M49,workshop,2021-09,11713,kWh,E723501 +M50,warehouse,2021-05,23480,kWh,E701885 +M09,workshop,2021-03,28365,kWh,E386098 +M57,warehouse,2021-01,44792,kWh,E810029 +M01,warehouse,2021-08,23482,kWh,E862671 +M49,workshop,2021-08,10957,kWh,E245119 +M09,workshop,2021-05,25341,kWh,E950283 +M50,warehouse,2021-08,25901,kWh,E535957 +M09,workshop,2021-12,31353,kWh,E908037 +M50,warehouse,2021-10,24890,kWh,E118531 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5555331e0da4290e57265250610cf2224f525be2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2021 monthly electricity consumption export for the meters of Marrow Vale Housing (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4c3b1c905fc184e62f41fd622edc5954b237ad00 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "eval"] +isced_f = "0521" +family = "data-quality" +split = "eval" +seed = 10017 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..9b5aa0896e973e6a8176771a7ad7a743825c1128 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M01.annual_kwh", + "type": "number", + "value": 329135.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M01.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M09.annual_kwh", + "type": "number", + "value": 348179.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M09.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M49.annual_kwh", + "type": "number", + "value": 140861.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M49.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M50.annual_kwh", + "type": "number", + "value": 311485.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M50.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M57.annual_kwh", + "type": "number", + "value": 548036.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M57.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1677697.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 644.24, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M50.2021-03", + "type": "number", + "value": 26663.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M57.2021-10", + "type": "number", + "value": 44998.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M50", + "M57" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-e0017/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..849850d1d9ebc97141e9c9d68cef451c00503af6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2022 electricity return + +- Electricity emission factor: 0.248 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..07bf275bb9d437b56cb63307562b6568f1f6ce61 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/environment/workdir/meter_readings.csv @@ -0,0 +1,67 @@ +meter_id,site,month,consumption,unit,invoice_ref +M27,depot,2022-04,25326,kWh,E278621 +M19,warehouse,2022-08,25445,kWh,E413284 +M19,warehouse,2022-05,25225,kWh,E575193 +M43,warehouse,2022-03,14695,kWh,E199399 +M27,depot,2022-09,24870,kWh,E649698 +M19,warehouse,2022-06,21434,kWh,E219566 +M17,depot,2022-01,6125,kWh,E398462 +M17,depot,2022-03,5410,kWh,E120724 +M17,depot,2022-02,5845,kWh,E393326 +M43,warehouse,2022-08,14853,kWh,E519975 +M43,warehouse,2022-02,14866,kWh,E676959 +M43,warehouse,2022-06,12926,kWh,E757503 +M19,warehouse,2022-06,21434,kWh,E219566 +M17,depot,2022-05,4776,kWh,E612644 +M43,warehouse,2022-11,15357,kWh,E862650 +M43,warehouse,2022-07,13678,kWh,E934405 +M17,depot,2022-09,5616,kWh,E201387 +M19,warehouse,2022-11,25284,kWh,E907408 +M19,warehouse,2022-02,27622,kWh,E666058 +M43,warehouse,2022-01,16901,kWh,E763852 +M39,warehouse,2022-11,34168,kWh,E669473 +M27,depot,2022-01,26297,kWh,E894803 +M27,depot,2022-02,28197,kWh,E682304 +M43,warehouse,2022-12,16741,kWh,E669191 +M39,warehouse,2022-09,31919,kWh,E604298 +M19,warehouse,2022-04,25585,kWh,E565715 +M39,warehouse,2022-06,27678,kWh,E680887 +M17,depot,2022-04,5799,kWh,E927640 +M17,depot,2022-12,5988,kWh,E417352 +M19,warehouse,2022-01,26682,kWh,E160299 +M43,warehouse,2022-05,13244,kWh,E987805 +M27,depot,2022-03,24227,kWh,E667716 +M43,warehouse,2022-07,13678,kWh,E934405 +M17,depot,2022-10,5540,kWh,E321700 +M27,depot,2022-04,25326,kWh,E278621 +M27,depot,2022-08,21428,kWh,E688035 +M39,warehouse,2022-10,31339,kWh,E168648 +M27,depot,2022-03,24227,kWh,E667716 +M17,depot,2022-01,6125,kWh,E398462 +M39,warehouse,2022-08,28538,kWh,E368349 +M27,depot,2022-05,23020,kWh,E980426 +M27,depot,2022-06,22304,kWh,E521996 +M19,warehouse,2022-03,27012,kWh,E751927 +M19,warehouse,2022-09,24104,kWh,E395237 +M39,warehouse,2022-07,28410,kWh,E535112 +M27,depot,2022-06,22304,kWh,E521996 +M39,warehouse,2022-12,39787,kWh,E818101 +M43,warehouse,2022-09,14372,kWh,E641578 +M17,depot,2022-08,4886,kWh,E451961 +M39,warehouse,2022-04,29691,kWh,E479431 +M43,warehouse,2022-04,13945,kWh,E136647 +M19,warehouse,2022-07,20750,kWh,E747511 +M39,warehouse,2022-05,28629,kWh,E909076 +M39,warehouse,2022-01,35231,kWh,E806779 +M17,depot,2022-11,6143,kWh,E671278 +M27,depot,2022-07,21190,kWh,E902919 +M19,warehouse,2022-12,28579,kWh,E595389 +M43,warehouse,2022-10,15347,kWh,E467814 +M27,depot,2022-12,29438,kWh,E703105 +M19,warehouse,2022-04,25585,kWh,E565715 +M17,depot,2022-07,4895,kWh,E532859 +M39,warehouse,2022-03,34484,kWh,E681233 +M17,depot,2022-06,4579,kWh,E762575 +M19,warehouse,2022-03,27012,kWh,E751927 +M19,warehouse,2022-10,29985,kWh,E585153 +M27,depot,2022-11,27236,kWh,E650992 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f7ba34b0a7bb80ff9ccd4b6c601373f6c35d11a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2022 monthly electricity consumption export for the meters of Kestrel Joinery (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..76c051764bd2aa1e1845570fe99ded072d2aa553 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 5 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..62f2ee4dfab98267a1d69615f24a060b5d457af4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M17.annual_kwh", + "type": "number", + "value": 65602.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M17.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M19.annual_kwh", + "type": "number", + "value": 307707.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M19.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M27.annual_kwh", + "type": "number", + "value": 299586.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M27.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M39.annual_kwh", + "type": "number", + "value": 384731.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M39.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M43.annual_kwh", + "type": "number", + "value": 176925.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M43.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1234551.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 306.17, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M27.2022-10", + "type": "number", + "value": 26053.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M39.2022-02", + "type": "number", + "value": 34857.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M27", + "M39" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0005/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..57ca01dca6719a9a1f094b5b53d902997574a8ef --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2022 electricity return + +- Electricity emission factor: 0.117 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..fedc0d8c503918d12b5e58990edee9e9df6dbdfd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/environment/workdir/meter_readings.csv @@ -0,0 +1,67 @@ +meter_id,site,month,consumption,unit,invoice_ref +M48,depot,2022-03,28708,kWh,E498753 +M48,depot,2022-05,27341,kWh,E287945 +M33,head_office,2022-06,27599,kWh,E665192 +M48,depot,2022-06,25145,kWh,E665520 +M48,depot,2022-11,34666,kWh,E603972 +M36,head_office,2022-12,4355,kWh,E478925 +M36,head_office,2022-11,4141,kWh,E799482 +M36,head_office,2022-07,3378,kWh,E169792 +M48,depot,2022-01,38418,kWh,E400173 +M02,depot,2022-06,16181,kWh,E524365 +M51,depot,2022-01,34145,kWh,E675698 +M48,depot,2022-10,32518,kWh,E592463 +M51,depot,2022-10,35961,kWh,E321282 +M51,depot,2022-08,27218,kWh,E764869 +M02,depot,2022-03,16282,kWh,E327119 +M36,head_office,2022-06,3935,kWh,E943523 +M02,depot,2022-10,19730,kWh,E675648 +M51,depot,2022-12,33416,kWh,E765832 +M36,head_office,2022-10,4262,kWh,E200416 +M02,depot,2022-10,19730,kWh,E675648 +M33,head_office,2022-01,42604,kWh,E686901 +M36,head_office,2022-02,4153,kWh,E418639 +M02,depot,2022-02,18332,kWh,E158075 +M48,depot,2022-08,32162,kWh,E972446 +M33,head_office,2022-12,39766,kWh,E217172 +M02,depot,2022-12,21437,kWh,E521221 +M02,depot,2022-11,17127,kWh,E787043 +M36,head_office,2022-05,3570,kWh,E616155 +M33,head_office,2022-08,32871,kWh,E766921 +M36,head_office,2022-06,3935,kWh,E943523 +M02,depot,2022-08,14693,kWh,E521171 +M33,head_office,2022-05,30819,kWh,E754728 +M02,depot,2022-09,16317,kWh,E324773 +M33,head_office,2022-03,34973,kWh,E835954 +M48,depot,2022-01,38418,kWh,E400173 +M36,head_office,2022-08,4056,kWh,E495654 +M02,depot,2022-04,16626,kWh,E965696 +M36,head_office,2022-09,4488,kWh,E113989 +M02,depot,2022-01,20877,kWh,E208239 +M48,depot,2022-09,32576,kWh,E712749 +M33,head_office,2022-09,30595,kWh,E274106 +M33,head_office,2022-07,32226,kWh,E168577 +M33,head_office,2022-02,36272,kWh,E649100 +M36,head_office,2022-01,5028,kWh,E117734 +M48,depot,2022-12,30458,kWh,E902201 +M51,depot,2022-05,28763,kWh,E471806 +M02,depot,2022-06,16181,kWh,E524365 +M51,depot,2022-03,28911,kWh,E759212 +M36,head_office,2022-02,4153,kWh,E418639 +M51,depot,2022-11,33065,kWh,E917324 +M33,head_office,2022-11,32875,kWh,E347778 +M36,head_office,2022-05,3570,kWh,E616155 +M02,depot,2022-05,16715,kWh,E438079 +M48,depot,2022-04,28163,kWh,E109422 +M51,depot,2022-06,26766,kWh,E829255 +M02,depot,2022-07,14171,kWh,E560201 +M33,head_office,2022-10,35705,kWh,E568373 +M36,head_office,2022-03,4341,kWh,E437625 +M36,head_office,2022-04,3896,kWh,E555922 +M51,depot,2022-07,26749,kWh,E519151 +M51,depot,2022-02,32519,kWh,E359973 +M51,depot,2022-09,29515,kWh,E183286 +M33,head_office,2022-04,31573,kWh,E695712 +M48,depot,2022-03,28708,kWh,E498753 +M48,depot,2022-02,30120,kWh,E318625 +M48,depot,2022-06,25145,kWh,E665520 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..72ac05c2cd2ebd7720a199366f5aaac00ed2b64b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2022 monthly electricity consumption export for the meters of Marrow Vale Housing (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b714a495acdb9575b4341a3408283265ca6cfa59 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 17 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d94a9cb5703698ea3a9b9c62afcc629dfb14c373 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M02.annual_kwh", + "type": "number", + "value": 208488.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M02.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M33.annual_kwh", + "type": "number", + "value": 407878.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M33.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M36.annual_kwh", + "type": "number", + "value": 49603.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M36.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M48.annual_kwh", + "type": "number", + "value": 368928.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M48.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M51.annual_kwh", + "type": "number", + "value": 365865.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M51.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1400762.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 163.89, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M48.2022-07", + "type": "number", + "value": 28653.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M51.2022-04", + "type": "number", + "value": 28837.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M48", + "M51" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0017/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..9e94c84afa3ec8ef25ee209b374a8338ef6a462b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2023 electricity return + +- Electricity emission factor: 0.412 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..fe473d73ac3dbb44e6e4d2fb485465eede734b5a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/environment/workdir/meter_readings.csv @@ -0,0 +1,61 @@ +meter_id,site,month,consumption,unit,invoice_ref +M35,head_office,2023-01,7708,kWh,E223796 +M30,head_office,2023-03,21411,kWh,E168886 +M35,head_office,2023-04,7777,kWh,E741622 +M26,depot,2023-01,9899,kWh,E398428 +M30,head_office,2023-07,19178,kWh,E872349 +M35,head_office,2023-06,7136,kWh,E907230 +M26,depot,2023-08,8772,kWh,E450601 +M35,head_office,2023-07,7020,kWh,E974515 +M30,head_office,2023-10,21855,kWh,E491438 +M56,head_office,2023-09,18890,kWh,E790626 +M35,head_office,2023-11,7982,kWh,E862470 +M56,head_office,2023-08,17503,kWh,E146071 +M57,head_office,2023-07,14555,kWh,E570441 +M35,head_office,2023-02,8679,kWh,E658414 +M26,depot,2023-02,9595,kWh,E278434 +M57,head_office,2023-08,12772,kWh,E460250 +M35,head_office,2023-10,8287,kWh,E759223 +M56,head_office,2023-01,16973,kWh,E197807 +M26,depot,2023-04,9636,kWh,E309991 +M56,head_office,2023-10,18296,kWh,E474875 +M30,head_office,2023-11,25194,kWh,E829280 +M30,head_office,2023-12,24478,kWh,E742016 +M56,head_office,2023-11,18788,kWh,E534204 +M26,depot,2023-12,10664,kWh,E933265 +M26,depot,2023-11,11173,kWh,E281814 +M56,head_office,2023-06,15739,kWh,E309400 +M35,head_office,2023-12,8859,kWh,E218011 +M30,head_office,2023-04,20526,kWh,E714197 +M35,head_office,2023-09,6710,kWh,E996498 +M30,head_office,2023-01,22250,kWh,E198800 +M30,head_office,2023-06,20339,kWh,E946184 +M57,head_office,2023-04,16288,kWh,E596196 +M56,head_office,2023-06,15739,kWh,E309400 +M57,head_office,2023-03,14326,kWh,E429876 +M30,head_office,2023-05,21957,kWh,E846781 +M57,head_office,2023-05,14231,kWh,E961351 +M26,depot,2023-06,7598,kWh,E874552 +M30,head_office,2023-09,23325,kWh,E891685 +M56,head_office,2023-04,17071,kWh,E146504 +M26,depot,2023-09,9111,kWh,E470460 +M57,head_office,2023-11,16513,kWh,E309926 +M57,head_office,2023-12,15921,kWh,E343730 +M35,head_office,2023-05,6666,kWh,E988506 +M56,head_office,2023-05,15532,kWh,E306971 +M35,head_office,2023-08,6579,kWh,E239126 +M26,depot,2023-03,10377,kWh,E182245 +M57,head_office,2023-09,15417,kWh,E881300 +M56,head_office,2023-07,16966,kWh,E585132 +M56,head_office,2023-12,22762,kWh,E346016 +M30,head_office,2023-02,26547,kWh,E618392 +M56,head_office,2023-02,20167,kWh,E406609 +M57,head_office,2023-06,13013,kWh,E118290 +M35,head_office,2023-03,8687,kWh,E685693 +M30,head_office,2023-08,22853,kWh,E546693 +M57,head_office,2023-10,15122,kWh,E397886 +M56,head_office,2023-03,16687,kWh,E933362 +M35,head_office,2023-07,7020,kWh,E974515 +M57,head_office,2023-01,16771,kWh,E202560 +M26,depot,2023-05,8968,kWh,E821683 +M26,depot,2023-07,8531,kWh,E418894 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c94ae4c2163619183b90159dc8f427fa587a7a4d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2023 monthly electricity consumption export for the meters of Brantholm Municipality (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1672a49e51f4c7efbe696723533af7e8b72a8f7f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 29 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e8f2d504fcb7ae8a0ff7a899e01915607c17428e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M26.annual_kwh", + "type": "number", + "value": 114466.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M26.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M30.annual_kwh", + "type": "number", + "value": 269913.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M30.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M35.annual_kwh", + "type": "number", + "value": 92090.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M35.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M56.annual_kwh", + "type": "number", + "value": 215374.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M56.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M57.annual_kwh", + "type": "number", + "value": 180477.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M57.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 872320.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 359.4, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M26.2023-10", + "type": "number", + "value": 10142.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M57.2023-02", + "type": "number", + "value": 15548.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M26", + "M57" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0029/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..d376a9661dddf5ebaa90edf481f78761a3009ca3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2022 electricity return + +- Electricity emission factor: 0.189 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..cb7c405d57cf89cb7821ed675e6a7f4873719473 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/environment/workdir/meter_readings.csv @@ -0,0 +1,71 @@ +meter_id,site,month,consumption,unit,invoice_ref +M46,warehouse,2022-11,3812,kWh,E767318 +M17,workshop,2022-06,15004,kWh,E719019 +M46,warehouse,2022-01,5054,kWh,E127060 +M11,warehouse,2022-05,11586,kWh,E909196 +M21,workshop,2022-09,34523,kWh,E162368 +M46,warehouse,2022-12,4665,kWh,E736195 +M29,workshop,2022-07,24440,kWh,E267332 +M46,warehouse,2022-03,4201,kWh,E943346 +M29,workshop,2022-05,27388,kWh,E439540 +M11,warehouse,2022-11,12293,kWh,E263325 +M17,workshop,2022-02,16722,kWh,E400457 +M29,workshop,2022-08,27724,kWh,E440029 +M11,warehouse,2022-06,10517,kWh,E650584 +M17,workshop,2022-02,16722,kWh,E400457 +M11,warehouse,2022-04,12063,kWh,E568999 +M17,workshop,2022-04,15267,kWh,E451046 +M17,workshop,2022-09,16631,kWh,E662974 +M29,workshop,2022-11,28597,kWh,E262799 +M17,workshop,2022-08,16462,kWh,E640011 +M11,warehouse,2022-07,11131,kWh,E604468 +M21,workshop,2022-05,28810,kWh,E146582 +M29,workshop,2022-04,28181,kWh,E173351 +M11,warehouse,2022-10,12867,kWh,E731180 +M17,workshop,2022-07,13847,kWh,E631273 +M29,workshop,2022-03,30888,kWh,E401729 +M29,workshop,2022-03,30888,kWh,E401729 +M21,workshop,2022-10,34918,kWh,E207130 +M29,workshop,2022-09,29255,kWh,E505470 +M46,warehouse,2022-05,4043,kWh,E406258 +M17,workshop,2022-08,16462,kWh,E640011 +M29,workshop,2022-04,28181,kWh,E173351 +M46,warehouse,2022-04,4253,kWh,E325261 +M17,workshop,2022-03,16107,kWh,E133012 +M17,workshop,2022-11,16349,kWh,E733770 +M11,warehouse,2022-12,14222,kWh,E535568 +M21,workshop,2022-03,32831,kWh,E258777 +M11,warehouse,2022-04,12063,kWh,E568999 +M29,workshop,2022-10,29298,kWh,E337109 +M17,workshop,2022-01,17175,kWh,E846207 +M11,warehouse,2022-02,14432,kWh,E716063 +M21,workshop,2022-11,33029,kWh,E141727 +M11,warehouse,2022-02,14432,kWh,E716063 +M11,warehouse,2022-08,11586,kWh,E751973 +M11,warehouse,2022-08,11586,kWh,E751973 +M17,workshop,2022-10,16770,kWh,E483423 +M46,warehouse,2022-07,3966,kWh,E472922 +M11,warehouse,2022-01,12560,kWh,E386553 +M46,warehouse,2022-06,3716,kWh,E221240 +M46,warehouse,2022-10,3848,kWh,E746387 +M17,workshop,2022-05,15825,kWh,E437038 +M29,workshop,2022-12,31183,kWh,E848204 +M21,workshop,2022-04,31530,kWh,E427168 +M21,workshop,2022-06,31527,kWh,E217440 +M46,warehouse,2022-09,3962,kWh,E995610 +M21,workshop,2022-04,31530,kWh,E427168 +M21,workshop,2022-07,30633,kWh,E531179 +M21,workshop,2022-02,35618,kWh,E643988 +M29,workshop,2022-11,28597,kWh,E262799 +M46,warehouse,2022-02,3883,kWh,E940221 +M21,workshop,2022-03,32831,kWh,E258777 +M29,workshop,2022-01,34343,kWh,E873538 +M29,workshop,2022-02,29630,kWh,E225758 +M17,workshop,2022-11,16349,kWh,E733770 +M46,warehouse,2022-08,3579,kWh,E251631 +M21,workshop,2022-12,32865,kWh,E565344 +M46,warehouse,2022-04,4253,kWh,E325261 +M17,workshop,2022-12,19999,kWh,E113809 +M11,warehouse,2022-09,11637,kWh,E307593 +M21,workshop,2022-01,41991,kWh,E674383 +M29,workshop,2022-06,25479,kWh,E571646 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f7ba34b0a7bb80ff9ccd4b6c601373f6c35d11a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2022 monthly electricity consumption export for the meters of Kestrel Joinery (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..275fe473a3ad0db40258818e973c9daef336e97b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 41 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..bab3e8c2ab11be93943e19834a5864b4af2c85f3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M11.annual_kwh", + "type": "number", + "value": 148141.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M11.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M17.annual_kwh", + "type": "number", + "value": 196158.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M17.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M21.annual_kwh", + "type": "number", + "value": 400853.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M21.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M29.annual_kwh", + "type": "number", + "value": 346406.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M29.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M46.annual_kwh", + "type": "number", + "value": 48982.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M46.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1140540.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 215.56, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M11.2022-03", + "type": "number", + "value": 13247.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M21.2022-08", + "type": "number", + "value": 32578.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M11", + "M21" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0041/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..5ba9a5d36bdf0af86378e3019aa1555b558f4f0d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2021 electricity return + +- Electricity emission factor: 0.425 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..c2e557cb435c23dad6de98a87f4386b1d167fe5b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/environment/workdir/meter_readings.csv @@ -0,0 +1,66 @@ +meter_id,site,month,consumption,unit,invoice_ref +M46,warehouse,2021-12,25098,kWh,E568760 +M14,depot,2021-01,8119,kWh,E363124 +M46,warehouse,2021-07,21788,kWh,E297120 +M24,warehouse,2021-03,42795,kWh,E750952 +M52,warehouse,2021-02,16839,kWh,E980676 +M14,depot,2021-06,6413,kWh,E213976 +M52,warehouse,2021-08,15188,kWh,E664011 +M37,warehouse,2021-10,33263,kWh,E190861 +M24,warehouse,2021-06,39560,kWh,E999150 +M14,depot,2021-06,6413,kWh,E213976 +M37,warehouse,2021-10,33263,kWh,E190861 +M37,warehouse,2021-11,37415,kWh,E711101 +M14,depot,2021-09,6618,kWh,E852039 +M37,warehouse,2021-03,34175,kWh,E707449 +M14,depot,2021-04,7219,kWh,E763078 +M37,warehouse,2021-02,39256,kWh,E475249 +M37,warehouse,2021-06,28996,kWh,E339094 +M46,warehouse,2021-06,20319,kWh,E733892 +M37,warehouse,2021-01,39561,kWh,E185763 +M24,warehouse,2021-06,39560,kWh,E999150 +M24,warehouse,2021-02,47367,kWh,E422882 +M37,warehouse,2021-04,31034,kWh,E183046 +M24,warehouse,2021-09,38612,kWh,E994901 +M46,warehouse,2021-10,25949,kWh,E762126 +M14,depot,2021-08,7712,kWh,E263652 +M24,warehouse,2021-07,40134,kWh,E298197 +M46,warehouse,2021-02,26833,kWh,E535932 +M52,warehouse,2021-11,18779,kWh,E602391 +M14,depot,2021-02,7919,kWh,E595712 +M52,warehouse,2021-07,13664,kWh,E581009 +M37,warehouse,2021-07,25839,kWh,E713462 +M52,warehouse,2021-12,18229,kWh,E465420 +M52,warehouse,2021-03,14522,kWh,E459689 +M24,warehouse,2021-04,45756,kWh,E567852 +M46,warehouse,2021-05,19753,kWh,E413489 +M14,depot,2021-03,7173,kWh,E624457 +M52,warehouse,2021-09,17027,kWh,E541876 +M37,warehouse,2021-12,41066,kWh,E236187 +M14,depot,2021-11,8863,kWh,E856712 +M37,warehouse,2021-01,39561,kWh,E185763 +M14,depot,2021-12,9743,kWh,E433957 +M24,warehouse,2021-11,44286,kWh,E111298 +M14,depot,2021-10,8853,kWh,E711952 +M14,depot,2021-04,7219,kWh,E763078 +M14,depot,2021-07,7042,kWh,E477964 +M46,warehouse,2021-03,20571,kWh,E102010 +M46,warehouse,2021-04,20121,kWh,E577188 +M52,warehouse,2021-01,17689,kWh,E627884 +M52,warehouse,2021-06,13731,kWh,E717502 +M24,warehouse,2021-08,38332,kWh,E261688 +M52,warehouse,2021-05,16328,kWh,E752529 +M24,warehouse,2021-05,40456,kWh,E609594 +M24,warehouse,2021-12,52455,kWh,E546075 +M46,warehouse,2021-11,26058,kWh,E842329 +M14,depot,2021-05,6977,kWh,E548608 +M52,warehouse,2021-04,13602,kWh,E741812 +M37,warehouse,2021-11,37415,kWh,E711101 +M46,warehouse,2021-09,23937,kWh,E168609 +M52,warehouse,2021-06,13731,kWh,E717502 +M24,warehouse,2021-10,43342,kWh,E877494 +M37,warehouse,2021-08,28841,kWh,E438339 +M37,warehouse,2021-05,30747,kWh,E438003 +M52,warehouse,2021-10,16654,kWh,E230042 +M24,warehouse,2021-01,45267,kWh,E890981 +M46,warehouse,2021-01,29111,kWh,E739551 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95ba116803fdd94fd1026349301a82af1b6545a0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2021 monthly electricity consumption export for the meters of Vessby Dairy Cooperative (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3073ca788541538b6317ca0b2e860f955c256828 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 53 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..36adc60475830b57d37aa53b273107ffb69c6eb0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M14.annual_kwh", + "type": "number", + "value": 92651.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M14.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M24.annual_kwh", + "type": "number", + "value": 518362.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M24.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M37.annual_kwh", + "type": "number", + "value": 401245.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M37.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M46.annual_kwh", + "type": "number", + "value": 282400.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M46.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M52.annual_kwh", + "type": "number", + "value": 192252.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M52.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1486910.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 631.94, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M37.2021-09", + "type": "number", + "value": 31052.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M46.2021-08", + "type": "number", + "value": 22862.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M37", + "M46" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0053/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..ded539aac66847dac253ad8e97b82800387a22b5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2024 electricity return + +- Electricity emission factor: 0.161 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..64debee64147b4f983711156fc03ad42d927a5b6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/environment/workdir/meter_readings.csv @@ -0,0 +1,70 @@ +meter_id,site,month,consumption,unit,invoice_ref +M11,warehouse,2024-03,12016,kWh,E285813 +M19,workshop,2024-10,38279,kWh,E120800 +M11,warehouse,2024-10,12954,kWh,E169798 +M11,warehouse,2024-02,11553,kWh,E171434 +M58,workshop,2024-04,10072,kWh,E673931 +M58,workshop,2024-01,13654,kWh,E623230 +M58,workshop,2024-08,10171,kWh,E857113 +M27,workshop,2024-12,24977,kWh,E794576 +M58,workshop,2024-03,10904,kWh,E650012 +M11,warehouse,2024-11,12897,kWh,E197571 +M23,warehouse,2024-01,37909,kWh,E176975 +M23,warehouse,2024-11,45582,kWh,E624311 +M19,workshop,2024-03,34986,kWh,E380053 +M27,workshop,2024-03,20516,kWh,E120860 +M11,warehouse,2024-01,13853,kWh,E674853 +M23,warehouse,2024-04,39262,kWh,E699216 +M19,workshop,2024-06,31634,kWh,E249387 +M27,workshop,2024-09,22458,kWh,E209716 +M23,warehouse,2024-09,40015,kWh,E124963 +M11,warehouse,2024-08,10470,kWh,E293333 +M58,workshop,2024-10,10127,kWh,E300755 +M11,warehouse,2024-02,11553,kWh,E171434 +M19,workshop,2024-11,43650,kWh,E935133 +M23,warehouse,2024-06,33702,kWh,E527848 +M27,workshop,2024-07,17362,kWh,E389528 +M27,workshop,2024-08,18961,kWh,E190769 +M58,workshop,2024-11,12431,kWh,E380815 +M58,workshop,2024-12,14383,kWh,E796734 +M58,workshop,2024-07,10411,kWh,E538844 +M23,warehouse,2024-07,35262,kWh,E897956 +M11,warehouse,2024-04,12955,kWh,E408713 +M27,workshop,2024-01,22429,kWh,E161374 +M19,workshop,2024-12,38481,kWh,E678560 +M19,workshop,2024-05,34626,kWh,E883635 +M19,workshop,2024-04,35069,kWh,E418524 +M23,warehouse,2024-03,40856,kWh,E390468 +M23,warehouse,2024-12,45642,kWh,E265918 +M11,warehouse,2024-09,11037,kWh,E289022 +M58,workshop,2024-12,14383,kWh,E796734 +M23,warehouse,2024-03,40856,kWh,E390468 +M11,warehouse,2024-12,13757,kWh,E987724 +M27,workshop,2024-03,20516,kWh,E120860 +M23,warehouse,2024-10,37309,kWh,E662312 +M58,workshop,2024-06,9771,kWh,E901692 +M11,warehouse,2024-07,10828,kWh,E967775 +M27,workshop,2024-04,18977,kWh,E281805 +M11,warehouse,2024-10,12954,kWh,E169798 +M27,workshop,2024-05,19182,kWh,E306011 +M27,workshop,2024-10,20735,kWh,E671589 +M11,warehouse,2024-05,12115,kWh,E439944 +M27,workshop,2024-06,19241,kWh,E560420 +M27,workshop,2024-11,25566,kWh,E713520 +M19,workshop,2024-08,32243,kWh,E515188 +M58,workshop,2024-02,11236,kWh,E741484 +M19,workshop,2024-01,40954,kWh,E975627 +M23,warehouse,2024-08,36667,kWh,E470198 +M11,warehouse,2024-04,12955,kWh,E408713 +M58,workshop,2024-03,10904,kWh,E650012 +M23,warehouse,2024-04,39262,kWh,E699216 +M23,warehouse,2024-02,37610,kWh,E842972 +M11,warehouse,2024-06,10048,kWh,E754159 +M19,workshop,2024-09,38827,kWh,E723999 +M58,workshop,2024-05,10041,kWh,E271959 +M27,workshop,2024-02,21086,kWh,E981075 +M27,workshop,2024-04,18977,kWh,E281805 +M23,warehouse,2024-06,33702,kWh,E527848 +M58,workshop,2024-09,9928,kWh,E584972 +M19,workshop,2024-02,36050,kWh,E746398 +M58,workshop,2024-08,10171,kWh,E857113 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f151733818076c630675a2499d0687d4e3b0896a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2024 monthly electricity consumption export for the meters of Marrow Vale Housing (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bbacf8cee558f953a3d6f4658a4de6bc256f1c0f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 65 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6aa19551327b0b6293b0f50dcaf0e51b3643864b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M11.annual_kwh", + "type": "number", + "value": 144483.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M11.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M19.annual_kwh", + "type": "number", + "value": 436737.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M19.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M23.annual_kwh", + "type": "number", + "value": 466298.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M23.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M27.annual_kwh", + "type": "number", + "value": 251490.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M27.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M58.annual_kwh", + "type": "number", + "value": 133129.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M58.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1432137.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 230.57, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M19.2024-07", + "type": "number", + "value": 31938.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M23.2024-05", + "type": "number", + "value": 36482.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M19", + "M23" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0065/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dae082297ac44d63f8203c953c1d77384e6c9063 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/workdir/data_rules.md @@ -0,0 +1,7 @@ +# Data rules for the 2023 electricity return + +- Electricity emission factor: 0.204 kg CO2e per kWh (use this value). + +1. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first. Keep one row and drop the rest. +2. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +3. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..7528397d24219eae89f2aa8f0bf677b0358c5d94 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/environment/workdir/meter_readings.csv @@ -0,0 +1,67 @@ +meter_id,site,month,consumption,unit,invoice_ref +M35,workshop,2023-07,27251,kWh,E438174 +M37,workshop,2023-08,35503,kWh,E385942 +M48,head_office,2023-11,22027,kWh,E782319 +M35,workshop,2023-10,28174,kWh,E543798 +M47,head_office,2023-09,3953,kWh,E484182 +M37,workshop,2023-05,40036,kWh,E889537 +M16,head_office,2023-05,11639,kWh,E664675 +M48,head_office,2023-07,19936,kWh,E312584 +M47,head_office,2023-07,4137,kWh,E443157 +M37,workshop,2023-12,52947,kWh,E633370 +M35,workshop,2023-11,30521,kWh,E113917 +M35,workshop,2023-01,32059,kWh,E997924 +M16,head_office,2023-03,13379,kWh,E664790 +M47,head_office,2023-03,3885,kWh,E250521 +M35,workshop,2023-04,29725,kWh,E435750 +M16,head_office,2023-11,15092,kWh,E870644 +M16,head_office,2023-09,13505,kWh,E260235 +M48,head_office,2023-05,21416,kWh,E471840 +M37,workshop,2023-11,45601,kWh,E642563 +M35,workshop,2023-09,31798,kWh,E284497 +M47,head_office,2023-01,4620,kWh,E701354 +M47,head_office,2023-01,4620,kWh,E701354 +M48,head_office,2023-10,21270,kWh,E333542 +M47,head_office,2023-06,3691,kWh,E625376 +M37,workshop,2023-01,43091,kWh,E992769 +M47,head_office,2023-03,3885,kWh,E250521 +M48,head_office,2023-02,22114,kWh,E914291 +M48,head_office,2023-01,25618,kWh,E636436 +M16,head_office,2023-12,14881,kWh,E591525 +M47,head_office,2023-12,4681,kWh,E825642 +M47,head_office,2023-02,4784,kWh,E520616 +M47,head_office,2023-08,3929,kWh,E664569 +M35,workshop,2023-08,28300,kWh,E453850 +M47,head_office,2023-04,4740,kWh,E216862 +M48,head_office,2023-04,19012,kWh,E832071 +M16,head_office,2023-10,13360,kWh,E965518 +M35,workshop,2023-02,32105,kWh,E376277 +M48,head_office,2023-01,25618,kWh,E636436 +M47,head_office,2023-05,3985,kWh,E601494 +M37,workshop,2023-06,35542,kWh,E897894 +M37,workshop,2023-09,40450,kWh,E952252 +M35,workshop,2023-12,34241,kWh,E684079 +M47,head_office,2023-07,4137,kWh,E443157 +M16,head_office,2023-01,14151,kWh,E796384 +M47,head_office,2023-11,4892,kWh,E333835 +M48,head_office,2023-03,19638,kWh,E928640 +M16,head_office,2023-10,13360,kWh,E965518 +M35,workshop,2023-03,32161,kWh,E997736 +M48,head_office,2023-07,19936,kWh,E312584 +M35,workshop,2023-06,27406,kWh,E702224 +M16,head_office,2023-07,11998,kWh,E123607 +M16,head_office,2023-02,12642,kWh,E325452 +M37,workshop,2023-03,42039,kWh,E882563 +M48,head_office,2023-08,20832,kWh,E221656 +M37,workshop,2023-02,40315,kWh,E358700 +M48,head_office,2023-12,25710,kWh,E662802 +M37,workshop,2023-07,34441,kWh,E524095 +M48,head_office,2023-09,22126,kWh,E757328 +M37,workshop,2023-10,42231,kWh,E624535 +M16,head_office,2023-04,12623,kWh,E628198 +M48,head_office,2023-06,17453,kWh,E158551 +M16,head_office,2023-11,15092,kWh,E870644 +M16,head_office,2023-08,10715,kWh,E222483 +M48,head_office,2023-09,22126,kWh,E757328 +M37,workshop,2023-04,39889,kWh,E259731 +M16,head_office,2023-06,11782,kWh,E751896 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00e4a1091eb91cf5d0db4e9e523d5579a324b14e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/instruction.md @@ -0,0 +1,16 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2023 monthly electricity consumption export for the meters of Ostervik Bakery Group (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..227be36e0dabd1ddc19bc45febbe302bc4ebee6c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 77 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4d0f1b2005d49c62bc15775de364ef1a5db9b09f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/checks.json @@ -0,0 +1,111 @@ +[ + { + "path": "meters.M16.annual_kwh", + "type": "number", + "value": 155767.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M16.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M35.annual_kwh", + "type": "number", + "value": 362306.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M35.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M37.annual_kwh", + "type": "number", + "value": 492085.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M37.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M47.annual_kwh", + "type": "number", + "value": 51719.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M47.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M48.annual_kwh", + "type": "number", + "value": 257152.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M48.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1319030.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 269.08, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M35.2023-05", + "type": "number", + "value": 28565.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M47.2023-10", + "type": "number", + "value": 4422.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M35", + "M47" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d2-t0077/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..be977e5547af340b92b1f534613f629dcfffabca --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2020 electricity return + +- Electricity emission factor: 0.229 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..4ab66f7f80cf262456f5f11ae4cd1bf8c45e56ad --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/environment/workdir/meter_readings.csv @@ -0,0 +1,78 @@ +meter_id,site,month,consumption,unit,invoice_ref +M09,workshop,2020-05,20330,kWh,E253973 +M04,head_office,2020-03,28002,kWh,E526959 +M27,head_office,2020-09,15116,kWh,E569096 +M35,depot,2020-01,44.534,MWh,E451296 +M04,head_office,2020-12,27143,kWh,E171905 +M35,depot,2020-10,38695,kWh,E610490 +M03,depot,2020-08,14212,kWh,E511224 +M35,depot,2020-11,46503,kWh,E103983 +M04,head_office,2020-02,27744,kWh,E599321 +M04,head_office,2020-04,27537,kWh,E842444 +M04,head_office,2020-11,28.805,MWh,E786633 +M56,head_office,2020-07,24.514,MWh,E216955 +M56,head_office,2020-03,27129,kWh,E411012 +M09,workshop,2020-02,25.187,MWh,E270075 +M03,depot,2020-05,14486,kWh,E615231 +M03,depot,2020-07,15597,kWh,E348027 +M09,workshop,2020-03,22.350,MWh,E592293 +M35,depot,2020-05,36173,kWh,E609478 +M04,head_office,2020-01,27695,kWh,E725301 +M03,depot,2020-06,13247,kWh,E576578 +M03,depot,2020-04,15.080,MWh,E371576 +M35,depot,2020-02,41.447,MWh,E214709 +M03,depot,2020-10,16013,kWh,E662906 +M56,head_office,2020-06,27.279,MWh,E628109 +M27,head_office,2020-05,13.968,MWh,E694774 +M35,depot,2020-09,36077,kWh,E560544 +M27,head_office,2020-04,15.148,MWh,E725868 +M09,workshop,2020-09,22718,kWh,E578651 +M56,head_office,2020-10,28.000,MWh,E939339 +M35,depot,2020-04,38.170,MWh,E380384 +M04,head_office,2020-10,24.993,MWh,E500871 +M03,depot,2020-12,18399,kWh,E349654 +M09,workshop,2020-01,26116,kWh,E259120 +M04,head_office,2020-07,22.920,MWh,E708546 +M35,depot,2020-07,31015,kWh,E295368 +M03,depot,2020-11,16680,kWh,E348843 +M27,head_office,2020-07,12448,kWh,E454953 +M27,head_office,2020-05,13968,kWh,E694774 +M56,head_office,2020-04,29369,kWh,E274298 +M09,workshop,2020-04,21.155,MWh,E409893 +M27,head_office,2020-08,13067,kWh,E104492 +M09,workshop,2020-07,18909,kWh,E872042 +M03,depot,2020-11,16680,kWh,E348843 +M27,head_office,2020-12,15983,kWh,E904454 +M27,head_office,2020-03,14.706,MWh,E268665 +M27,head_office,2020-10,14.744,MWh,E312157 +M56,head_office,2020-01,35222,kWh,E425417 +M56,head_office,2020-11,28525,kWh,E431981 +M27,head_office,2020-06,11.436,MWh,E510387 +M09,workshop,2020-07,18.909,MWh,E872042 +M35,depot,2020-12,41856,kWh,E751148 +M04,head_office,2020-06,23435,kWh,E118400 +M35,depot,2020-06,34.311,MWh,E401145 +M03,depot,2020-09,13788,kWh,E415405 +M09,workshop,2020-06,20.136,MWh,E725869 +M35,depot,2020-08,37742,kWh,E911810 +M09,workshop,2020-10,22657,kWh,E836059 +M09,workshop,2020-04,21155,kWh,E409893 +M04,head_office,2020-05,22242,kWh,E205228 +M56,head_office,2020-02,34169,kWh,E623647 +M27,head_office,2020-02,14071,kWh,E646582 +M56,head_office,2020-12,29146,kWh,E468615 +M03,depot,2020-05,14.486,MWh,E615231 +M27,head_office,2020-01,14827,kWh,E396846 +M09,workshop,2020-08,22248,kWh,E282890 +M27,head_office,2020-07,12.448,MWh,E454953 +M56,head_office,2020-08,27000,kWh,E435590 +M56,head_office,2020-09,29.021,MWh,E597566 +M09,workshop,2020-12,27.190,MWh,E324793 +M35,depot,2020-03,37.014,MWh,E868615 +M27,head_office,2020-04,15.148,MWh,E725868 +M09,workshop,2020-09,22718,kWh,E578651 +M03,depot,2020-03,16.843,MWh,E648540 +M09,workshop,2020-11,25297,kWh,E338061 +M03,depot,2020-01,20.499,MWh,E456177 +M04,head_office,2020-09,23962,kWh,E843637 +M04,head_office,2020-08,24.983,MWh,E213383 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f2f17eaacaecb524c4d24f77b3c39cca209c6cea --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2020 monthly electricity consumption export for the meters of Lindqvist Castings (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d960ea2bddd359e65397b81b070e5e5bab561c6a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "eval"] +isced_f = "0521" +family = "data-quality" +split = "eval" +seed = 10009 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..73512cc46827e71137fc5ef7c6d9926f90cae7d9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/checks.json @@ -0,0 +1,159 @@ +[ + { + "path": "meters.M03.annual_kwh", + "type": "number", + "value": 193515.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M03.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M04.annual_kwh", + "type": "number", + "value": 309461.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M04.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M09.annual_kwh", + "type": "number", + "value": 274293.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M09.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M27.annual_kwh", + "type": "number", + "value": 170877.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M27.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M35.annual_kwh", + "type": "number", + "value": 463537.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M35.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M56.annual_kwh", + "type": "number", + "value": 347698.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M56.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1759381.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 402.9, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M03.2020-02", + "type": "number", + "value": 18671.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M27.2020-11", + "type": "number", + "value": 15363.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M56.2020-05", + "type": "number", + "value": 28324.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M03", + "M27", + "M56" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.depot", + "type": "number", + "value": 150.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.head_office", + "type": "number", + "value": 189.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.workshop", + "type": "number", + "value": 62.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2020-01", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0009/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..af66df6c010d1df64e28ce1922b3f9805659f415 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2022 electricity return + +- Electricity emission factor: 0.220 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..b24fd4269511ea00a03a76bf548b2cdb70e27dc9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/environment/workdir/meter_readings.csv @@ -0,0 +1,75 @@ +meter_id,site,month,consumption,unit,invoice_ref +M50,head_office,2022-01,16.024,MWh,E907602 +M16,depot,2022-09,30823,kWh,E720094 +M16,depot,2022-05,26.317,MWh,E766225 +M47,workshop,2022-11,18165,kWh,E764371 +M16,depot,2022-03,31854,kWh,E263626 +M50,head_office,2022-05,13409,kWh,E753820 +M34,workshop,2022-09,27594,kWh,E745678 +M47,workshop,2022-01,19.999,MWh,E436258 +M26,workshop,2022-01,24.439,MWh,E295206 +M26,workshop,2022-04,23.342,MWh,E391811 +M47,workshop,2022-08,17216,kWh,E468699 +M24,head_office,2022-05,22.170,MWh,E815454 +M47,workshop,2022-06,15.104,MWh,E673316 +M16,depot,2022-01,30298,kWh,E928459 +M47,workshop,2022-02,16603,kWh,E237729 +M16,depot,2022-04,30265,kWh,E943919 +M26,workshop,2022-05,23.154,MWh,E142259 +M24,head_office,2022-08,24.107,MWh,E634722 +M34,workshop,2022-02,32158,kWh,E303285 +M24,head_office,2022-07,21503,kWh,E615705 +M24,head_office,2022-12,26703,kWh,E812463 +M24,head_office,2022-09,22088,kWh,E223274 +M16,depot,2022-11,31586,kWh,E718728 +M24,head_office,2022-11,23.514,MWh,E387777 +M47,workshop,2022-07,15247,kWh,E656284 +M50,head_office,2022-06,13034,kWh,E615722 +M50,head_office,2022-12,17011,kWh,E604199 +M34,workshop,2022-10,31282,kWh,E849728 +M47,workshop,2022-03,17259,kWh,E233586 +M47,workshop,2022-12,19.254,MWh,E571298 +M47,workshop,2022-10,16997,kWh,E257133 +M34,workshop,2022-04,31096,kWh,E987028 +M16,depot,2022-07,26503,kWh,E134498 +M26,workshop,2022-12,26036,kWh,E901314 +M24,head_office,2022-03,24459,kWh,E440407 +M26,workshop,2022-10,25055,kWh,E847550 +M16,depot,2022-08,30829,kWh,E292660 +M24,head_office,2022-10,26358,kWh,E498378 +M47,workshop,2022-04,16.331,MWh,E407630 +M50,head_office,2022-08,12889,kWh,E306939 +M26,workshop,2022-02,24252,kWh,E564552 +M16,depot,2022-06,28.042,MWh,E442574 +M34,workshop,2022-05,27615,kWh,E173841 +M50,head_office,2022-02,14632,kWh,E875740 +M47,workshop,2022-09,17098,kWh,E695242 +M50,head_office,2022-10,16712,kWh,E238529 +M50,head_office,2022-09,14968,kWh,E888167 +M34,workshop,2022-06,28927,kWh,E685263 +M34,workshop,2022-01,32.585,MWh,E221509 +M24,head_office,2022-08,24107,kWh,E634722 +M24,head_office,2022-06,20531,kWh,E156541 +M24,head_office,2022-09,22.088,MWh,E223274 +M50,head_office,2022-04,15196,kWh,E303713 +M16,depot,2022-02,33.612,MWh,E360411 +M24,head_office,2022-01,23944,kWh,E282671 +M16,depot,2022-12,30170,kWh,E135322 +M26,workshop,2022-03,22506,kWh,E807593 +M50,head_office,2022-03,13974,kWh,E384485 +M34,workshop,2022-08,29861,kWh,E236361 +M47,workshop,2022-05,15804,kWh,E999242 +M34,workshop,2022-12,39163,kWh,E995049 +M24,head_office,2022-05,22170,kWh,E815454 +M50,head_office,2022-11,17485,kWh,E738679 +M47,workshop,2022-10,16997,kWh,E257133 +M26,workshop,2022-09,23.644,MWh,E229142 +M26,workshop,2022-07,19594,kWh,E645374 +M34,workshop,2022-09,27594,kWh,E745678 +M26,workshop,2022-06,20478,kWh,E247366 +M24,head_office,2022-04,25101,kWh,E780571 +M34,workshop,2022-03,31.618,MWh,E254494 +M34,workshop,2022-04,31096,kWh,E987028 +M16,depot,2022-10,33229,kWh,E205952 +M50,head_office,2022-07,14174,kWh,E839725 +M34,workshop,2022-11,30986,kWh,E211859 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c802a223dc722fff07ea2d348229112a30ebf669 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2022 monthly electricity consumption export for the meters of Brantholm Municipality (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6f8f912942285503cde2accf26838c3c27e19ca1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "eval"] +isced_f = "0521" +family = "data-quality" +split = "eval" +seed = 10021 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b386fbd1b747b3af183fa943789729263359cc44 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/checks.json @@ -0,0 +1,166 @@ +[ + { + "path": "meters.M16.annual_kwh", + "type": "number", + "value": 363528.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M16.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M24.annual_kwh", + "type": "number", + "value": 284679.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M24.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M26.annual_kwh", + "type": "number", + "value": 279664.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M26.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M34.annual_kwh", + "type": "number", + "value": 372279.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M34.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M47.annual_kwh", + "type": "number", + "value": 205077.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M47.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M50.annual_kwh", + "type": "number", + "value": 179508.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M50.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1684736.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 370.64, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M24.2022-02", + "type": "number", + "value": 24201.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M26.2022-08", + "type": "number", + "value": 21619.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M26.2022-11", + "type": "number", + "value": 25545.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M34.2022-07", + "type": "number", + "value": 29394.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M24", + "M26", + "M34" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.depot", + "type": "number", + "value": 79.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.head_office", + "type": "number", + "value": 102.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.workshop", + "type": "number", + "value": 188.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2022-12", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-e0021/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..fba59c373f11bb2629d63ff813520b83e7980e6c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2023 electricity return + +- Electricity emission factor: 0.368 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..030b2ddf30106a8d0ad9da640b76e47785ee5ef9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/environment/workdir/meter_readings.csv @@ -0,0 +1,80 @@ +meter_id,site,month,consumption,unit,invoice_ref +M44,depot,2023-08,11552,kWh,E609699 +M11,warehouse,2023-08,6.060,MWh,E192219 +M09,depot,2023-01,51678,kWh,E259867 +M11,warehouse,2023-03,7358,kWh,E768879 +M44,depot,2023-02,12053,kWh,E868500 +M59,warehouse,2023-05,11274,kWh,E272603 +M44,depot,2023-11,13.772,MWh,E934828 +M25,workshop,2023-04,39.080,MWh,E200886 +M42,warehouse,2023-02,36661,kWh,E124502 +M59,warehouse,2023-09,13218,kWh,E967654 +M59,warehouse,2023-04,13005,kWh,E490253 +M44,depot,2023-01,12351,kWh,E536420 +M09,depot,2023-10,42.778,MWh,E714736 +M44,depot,2023-05,11566,kWh,E730902 +M25,workshop,2023-12,38.684,MWh,E252244 +M11,warehouse,2023-04,7702,kWh,E204646 +M11,warehouse,2023-02,6903,kWh,E899667 +M44,depot,2023-03,11628,kWh,E578311 +M25,workshop,2023-10,42781,kWh,E629276 +M09,depot,2023-09,40.167,MWh,E236926 +M44,depot,2023-12,14208,kWh,E973161 +M09,depot,2023-03,48071,kWh,E442594 +M44,depot,2023-10,12106,kWh,E802148 +M42,warehouse,2023-12,36867,kWh,E344671 +M11,warehouse,2023-07,5.930,MWh,E472787 +M25,workshop,2023-03,41411,kWh,E592278 +M25,workshop,2023-01,43027,kWh,E358742 +M59,warehouse,2023-06,11769,kWh,E737223 +M11,warehouse,2023-08,6.060,MWh,E192219 +M11,warehouse,2023-10,7682,kWh,E941731 +M44,depot,2023-04,11437,kWh,E663659 +M59,warehouse,2023-02,13.241,MWh,E893642 +M25,workshop,2023-08,37.091,MWh,E506630 +M11,warehouse,2023-12,8820,kWh,E570397 +M42,warehouse,2023-10,36064,kWh,E962558 +M09,depot,2023-06,40071,kWh,E179699 +M09,depot,2023-11,41.532,MWh,E649788 +M44,depot,2023-06,9569,kWh,E857452 +M42,warehouse,2023-09,31.363,MWh,E989475 +M59,warehouse,2023-07,11824,kWh,E550727 +M42,warehouse,2023-08,32148,kWh,E101914 +M11,warehouse,2023-03,7358,kWh,E768879 +M25,workshop,2023-11,46525,kWh,E704803 +M11,warehouse,2023-05,7087,kWh,E184768 +M25,workshop,2023-09,36990,kWh,E813290 +M44,depot,2023-10,12106,kWh,E802148 +M11,warehouse,2023-09,6627,kWh,E512047 +M11,warehouse,2023-11,7733,kWh,E672885 +M42,warehouse,2023-10,36064,kWh,E962558 +M25,workshop,2023-06,31279,kWh,E370739 +M59,warehouse,2023-08,12586,kWh,E459355 +M42,warehouse,2023-05,33563,kWh,E354958 +M09,depot,2023-08,37.430,MWh,E615800 +M59,warehouse,2023-01,13557,kWh,E721422 +M11,warehouse,2023-06,6.613,MWh,E566139 +M11,warehouse,2023-01,8.556,MWh,E750687 +M44,depot,2023-01,12351,kWh,E536420 +M25,workshop,2023-05,34212,kWh,E253799 +M44,depot,2023-07,10.856,MWh,E909271 +M59,warehouse,2023-06,11769,kWh,E737223 +M09,depot,2023-05,39720,kWh,E253908 +M42,warehouse,2023-07,33.253,MWh,E819947 +M44,depot,2023-09,10267,kWh,E564346 +M09,depot,2023-04,40258,kWh,E512052 +M59,warehouse,2023-11,12599,kWh,E134025 +M42,warehouse,2023-04,29696,kWh,E588015 +M42,warehouse,2023-01,39.044,MWh,E767636 +M09,depot,2023-07,38678,kWh,E257434 +M25,workshop,2023-07,29664,kWh,E111544 +M42,warehouse,2023-03,35384,kWh,E482571 +M09,depot,2023-01,51.678,MWh,E259867 +M09,depot,2023-02,45.457,MWh,E755232 +M09,depot,2023-12,46.657,MWh,E463179 +M59,warehouse,2023-11,12599,kWh,E134025 +M59,warehouse,2023-10,11234,kWh,E554746 +M59,warehouse,2023-08,12.586,MWh,E459355 +M44,depot,2023-09,10267,kWh,E564346 +M59,warehouse,2023-12,13577,kWh,E902517 +M42,warehouse,2023-11,36676,kWh,E202142 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82b986ab162e5a2577096d4fff0db02dbf59ad6c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2023 monthly electricity consumption export for the meters of Tarnwick Borough Council (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0dfd8bfb75d73619a489391949889765f09f4051 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 9 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6376edfef22a10af07b8842f8b18bf5c9f590ce9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/checks.json @@ -0,0 +1,159 @@ +[ + { + "path": "meters.M09.annual_kwh", + "type": "number", + "value": 512497.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M09.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M11.annual_kwh", + "type": "number", + "value": 87071.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M11.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M25.annual_kwh", + "type": "number", + "value": 462963.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M25.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M42.annual_kwh", + "type": "number", + "value": 414127.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M42.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M44.annual_kwh", + "type": "number", + "value": 141365.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M44.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M59.annual_kwh", + "type": "number", + "value": 151007.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M59.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1769030.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 651.0, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M25.2023-02", + "type": "number", + "value": 42219.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M42.2023-06", + "type": "number", + "value": 33408.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M59.2023-03", + "type": "number", + "value": 13123.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M25", + "M42", + "M59" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.depot", + "type": "number", + "value": 240.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.warehouse", + "type": "number", + "value": 240.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.workshop", + "type": "number", + "value": 170.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2023-01", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0009/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..4a3553d224f751e9cc49c7a36cb860181c0589f2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2023 electricity return + +- Electricity emission factor: 0.450 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..9b107649b0fb1f5ca468611cb21d6161bb68bfdb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/environment/workdir/meter_readings.csv @@ -0,0 +1,77 @@ +meter_id,site,month,consumption,unit,invoice_ref +M32,head_office,2023-06,27240,kWh,E752947 +M32,head_office,2023-04,27808,kWh,E453262 +M15,depot,2023-10,30.765,MWh,E350970 +M22,head_office,2023-09,26845,kWh,E360906 +M32,head_office,2023-10,29.075,MWh,E270845 +M35,head_office,2023-04,15267,kWh,E579681 +M15,depot,2023-01,32.421,MWh,E598344 +M35,head_office,2023-09,15.543,MWh,E524387 +M35,head_office,2023-02,19.179,MWh,E620209 +M45,warehouse,2023-06,17.318,MWh,E267307 +M24,warehouse,2023-12,16835,kWh,E204713 +M15,depot,2023-12,31735,kWh,E957165 +M45,warehouse,2023-11,17753,kWh,E890805 +M35,head_office,2023-02,19179,kWh,E620209 +M45,warehouse,2023-08,15982,kWh,E872312 +M32,head_office,2023-01,33.614,MWh,E626065 +M35,head_office,2023-07,12628,kWh,E993104 +M24,warehouse,2023-10,14.273,MWh,E778377 +M45,warehouse,2023-09,17688,kWh,E491605 +M32,head_office,2023-10,29.075,MWh,E270845 +M22,head_office,2023-05,30.606,MWh,E360404 +M45,warehouse,2023-04,16312,kWh,E379076 +M35,head_office,2023-01,15372,kWh,E135389 +M24,warehouse,2023-08,13988,kWh,E531073 +M32,head_office,2023-02,35482,kWh,E276218 +M32,head_office,2023-05,27.352,MWh,E741138 +M22,head_office,2023-12,33.136,MWh,E791298 +M22,head_office,2023-07,24.828,MWh,E379739 +M45,warehouse,2023-03,18318,kWh,E531225 +M45,warehouse,2023-10,16150,kWh,E672755 +M45,warehouse,2023-01,21088,kWh,E450110 +M45,warehouse,2023-07,15677,kWh,E856384 +M15,depot,2023-08,29001,kWh,E144531 +M24,warehouse,2023-01,17480,kWh,E385360 +M24,warehouse,2023-02,15696,kWh,E516429 +M32,head_office,2023-07,25.824,MWh,E457354 +M35,head_office,2023-08,14433,kWh,E839352 +M22,head_office,2023-06,26911,kWh,E890331 +M35,head_office,2023-11,16896,kWh,E990078 +M35,head_office,2023-03,16.975,MWh,E575987 +M15,depot,2023-07,27934,kWh,E716550 +M32,head_office,2023-03,29953,kWh,E221264 +M35,head_office,2023-12,16728,kWh,E373083 +M22,head_office,2023-08,28971,kWh,E122035 +M24,warehouse,2023-11,15.475,MWh,E818828 +M35,head_office,2023-06,14220,kWh,E310739 +M24,warehouse,2023-09,14.619,MWh,E694836 +M22,head_office,2023-04,31.488,MWh,E953950 +M15,depot,2023-06,25.335,MWh,E831623 +M32,head_office,2023-01,33.614,MWh,E626065 +M45,warehouse,2023-12,21001,kWh,E964968 +M22,head_office,2023-03,28.747,MWh,E212310 +M45,warehouse,2023-05,15584,kWh,E511071 +M24,warehouse,2023-03,15717,kWh,E320963 +M24,warehouse,2023-05,13949,kWh,E157547 +M24,warehouse,2023-07,13849,kWh,E171997 +M15,depot,2023-03,33.181,MWh,E304928 +M22,head_office,2023-01,32161,kWh,E151811 +M32,head_office,2023-08,26313,kWh,E931193 +M32,head_office,2023-09,27840,kWh,E487352 +M22,head_office,2023-10,31323,kWh,E429357 +M24,warehouse,2023-11,15475,kWh,E818828 +M32,head_office,2023-03,29953,kWh,E221264 +M22,head_office,2023-02,28971,kWh,E598261 +M15,depot,2023-05,27020,kWh,E553732 +M15,depot,2023-02,31.694,MWh,E251826 +M15,depot,2023-11,31837,kWh,E973821 +M32,head_office,2023-12,37185,kWh,E968643 +M15,depot,2023-04,29.952,MWh,E205605 +M45,warehouse,2023-12,21001,kWh,E964968 +M45,warehouse,2023-02,21.113,MWh,E288593 +M15,depot,2023-09,29.625,MWh,E655387 +M35,head_office,2023-05,14483,kWh,E599647 +M32,head_office,2023-11,36412,kWh,E247541 +M45,warehouse,2023-06,17.318,MWh,E267307 +M15,depot,2023-07,27934,kWh,E716550 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27de8d35687e59cfacbc11b5159a23f3ca748b29 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2023 monthly electricity consumption export for the meters of Brantholm Municipality (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..da453d0fe3d9679be7873db13a0d23051f7fd368 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 21 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..554b964846c3749c7e07c8ac1feb82ad752a90b0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/checks.json @@ -0,0 +1,166 @@ +[ + { + "path": "meters.M15.annual_kwh", + "type": "number", + "value": 360500.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M15.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M22.annual_kwh", + "type": "number", + "value": 356216.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M22.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M24.annual_kwh", + "type": "number", + "value": 180613.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M24.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M32.annual_kwh", + "type": "number", + "value": 364098.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M32.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M35.annual_kwh", + "type": "number", + "value": 187943.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M35.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M45.annual_kwh", + "type": "number", + "value": 213984.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M45.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1663355.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 748.51, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M22.2023-11", + "type": "number", + "value": 32229.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M24.2023-04", + "type": "number", + "value": 14833.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M24.2023-06", + "type": "number", + "value": 13899.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M35.2023-10", + "type": "number", + "value": 16219.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M22", + "M24", + "M35" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.depot", + "type": "number", + "value": 162.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.head_office", + "type": "number", + "value": 408.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.warehouse", + "type": "number", + "value": 177.57, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2023-12", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0021/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..570434dfccea7bf52840f1796f19af217b834a8a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2022 electricity return + +- Electricity emission factor: 0.415 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..5464140d47bb871cec8fb337c9af60f3049b0c4f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/environment/workdir/meter_readings.csv @@ -0,0 +1,77 @@ +meter_id,site,month,consumption,unit,invoice_ref +M21,workshop,2022-05,8670,kWh,E519384 +M21,workshop,2022-03,9.890,MWh,E193460 +M03,warehouse,2022-03,39.300,MWh,E618402 +M03,warehouse,2022-10,34530,kWh,E927058 +M25,head_office,2022-03,23007,kWh,E237686 +M25,head_office,2022-01,23440,kWh,E519637 +M21,workshop,2022-01,10.663,MWh,E628433 +M03,warehouse,2022-05,35.874,MWh,E241243 +M21,workshop,2022-07,8.367,MWh,E105823 +M45,workshop,2022-07,12358,kWh,E698978 +M45,workshop,2022-11,16543,kWh,E670015 +M03,warehouse,2022-02,37128,kWh,E160973 +M21,workshop,2022-09,8.766,MWh,E627269 +M25,head_office,2022-04,24118,kWh,E903139 +M01,head_office,2022-03,27.542,MWh,E910367 +M22,warehouse,2022-01,33.407,MWh,E771318 +M01,head_office,2022-02,28713,kWh,E545436 +M45,workshop,2022-04,15.148,MWh,E611667 +M21,workshop,2022-10,8.654,MWh,E282713 +M03,warehouse,2022-11,36.587,MWh,E210240 +M22,warehouse,2022-05,23.960,MWh,E562589 +M21,workshop,2022-11,9.903,MWh,E574117 +M22,warehouse,2022-08,27898,kWh,E716098 +M25,head_office,2022-05,21722,kWh,E733279 +M25,head_office,2022-12,25635,kWh,E898764 +M01,head_office,2022-11,31879,kWh,E979065 +M25,head_office,2022-09,21.638,MWh,E383015 +M01,head_office,2022-01,33082,kWh,E805149 +M22,warehouse,2022-02,28799,kWh,E821663 +M22,warehouse,2022-11,28229,kWh,E323335 +M22,warehouse,2022-06,22.819,MWh,E183921 +M45,workshop,2022-10,15026,kWh,E425507 +M01,head_office,2022-04,27555,kWh,E294125 +M25,head_office,2022-10,25911,kWh,E547266 +M21,workshop,2022-06,8089,kWh,E139440 +M22,warehouse,2022-04,26796,kWh,E155518 +M21,workshop,2022-04,9264,kWh,E913933 +M45,workshop,2022-06,14066,kWh,E262588 +M03,warehouse,2022-10,34530,kWh,E927058 +M45,workshop,2022-11,16.543,MWh,E670015 +M22,warehouse,2022-03,28.273,MWh,E640715 +M22,warehouse,2022-07,23910,kWh,E668818 +M01,head_office,2022-10,26593,kWh,E137930 +M25,head_office,2022-07,20580,kWh,E366785 +M03,warehouse,2022-12,42.430,MWh,E283605 +M03,warehouse,2022-08,29930,kWh,E271743 +M45,workshop,2022-08,14359,kWh,E359981 +M21,workshop,2022-08,8.482,MWh,E545625 +M01,head_office,2022-09,26947,kWh,E962070 +M03,warehouse,2022-01,34.028,MWh,E242801 +M22,warehouse,2022-12,34.046,MWh,E621991 +M45,workshop,2022-01,17726,kWh,E483095 +M22,warehouse,2022-09,28.573,MWh,E413809 +M45,workshop,2022-04,15.148,MWh,E611667 +M03,warehouse,2022-07,28734,kWh,E131941 +M03,warehouse,2022-06,28751,kWh,E505095 +M22,warehouse,2022-10,28205,kWh,E224780 +M45,workshop,2022-02,15.800,MWh,E976364 +M03,warehouse,2022-12,42430,kWh,E283605 +M01,head_office,2022-12,32176,kWh,E109627 +M03,warehouse,2022-06,28.751,MWh,E505095 +M25,head_office,2022-02,24191,kWh,E328972 +M01,head_office,2022-05,24666,kWh,E740933 +M21,workshop,2022-02,9.372,MWh,E757458 +M45,workshop,2022-03,15.849,MWh,E610270 +M22,warehouse,2022-09,28.573,MWh,E413809 +M21,workshop,2022-12,12.267,MWh,E554727 +M01,head_office,2022-08,25.437,MWh,E976175 +M25,head_office,2022-11,23.176,MWh,E115015 +M45,workshop,2022-12,17.785,MWh,E879204 +M01,head_office,2022-07,26.233,MWh,E183875 +M01,head_office,2022-05,24.666,MWh,E740933 +M25,head_office,2022-06,20.968,MWh,E354574 +M01,head_office,2022-06,25389,kWh,E412104 +M45,workshop,2022-05,14110,kWh,E290718 +M22,warehouse,2022-01,33407,kWh,E771318 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..64785d1bc4a080a19e89fb777be1aaf44e553330 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2022 monthly electricity consumption export for the meters of Harlow Fold Logistics (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c30cb2037c5687ef71f1973e5365db99026fc62 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 33 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..86ff80017046e6ad47c15a04e5f3a4d13283bcd6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/checks.json @@ -0,0 +1,166 @@ +[ + { + "path": "meters.M01.annual_kwh", + "type": "number", + "value": 336212.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M01.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M03.annual_kwh", + "type": "number", + "value": 417109.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M03.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M21.annual_kwh", + "type": "number", + "value": 112387.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M21.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M22.annual_kwh", + "type": "number", + "value": 334915.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M22.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M25.annual_kwh", + "type": "number", + "value": 275495.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M25.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M45.annual_kwh", + "type": "number", + "value": 183462.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M45.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1659580.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 688.73, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M03.2022-04", + "type": "number", + "value": 37587.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M03.2022-09", + "type": "number", + "value": 32230.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M25.2022-08", + "type": "number", + "value": 21109.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M45.2022-09", + "type": "number", + "value": 14692.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M03", + "M25", + "M45" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.head_office", + "type": "number", + "value": 253.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.warehouse", + "type": "number", + "value": 312.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.workshop", + "type": "number", + "value": 122.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2022-12", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0033/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..3c6ec7c600a5b934177caee21442806f852ea5ef --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2024 electricity return + +- Electricity emission factor: 0.316 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..954846113614da3578c0f29e3c2873b3cb9f06eb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/environment/workdir/meter_readings.csv @@ -0,0 +1,81 @@ +meter_id,site,month,consumption,unit,invoice_ref +M55,depot,2024-08,14919,kWh,E344117 +M39,depot,2024-01,21.591,MWh,E532975 +M44,depot,2024-12,9.307,MWh,E552233 +M55,depot,2024-12,19735,kWh,E503307 +M44,depot,2024-05,7507,kWh,E837712 +M40,head_office,2024-01,38433,kWh,E486117 +M40,head_office,2024-06,30.716,MWh,E929408 +M39,depot,2024-11,21.896,MWh,E405987 +M44,depot,2024-07,7.363,MWh,E863378 +M55,depot,2024-10,18.151,MWh,E379412 +M44,depot,2024-10,7276,kWh,E527279 +M41,workshop,2024-11,3060,kWh,E648257 +M55,depot,2024-05,16912,kWh,E512526 +M55,depot,2024-04,16.371,MWh,E294647 +M55,depot,2024-05,16912,kWh,E512526 +M41,workshop,2024-07,2843,kWh,E553227 +M44,depot,2024-09,7.383,MWh,E152260 +M39,depot,2024-02,19.827,MWh,E540688 +M40,head_office,2024-05,37.071,MWh,E127734 +M51,head_office,2024-06,9029,kWh,E894469 +M51,head_office,2024-10,11.137,MWh,E458062 +M51,head_office,2024-01,11339,kWh,E583359 +M44,depot,2024-03,8.284,MWh,E321848 +M40,head_office,2024-05,37071,kWh,E127734 +M55,depot,2024-01,19.154,MWh,E656188 +M44,depot,2024-03,8.284,MWh,E321848 +M39,depot,2024-06,18496,kWh,E512643 +M40,head_office,2024-07,29.903,MWh,E684599 +M41,workshop,2024-08,2816,kWh,E315404 +M44,depot,2024-06,6944,kWh,E208994 +M44,depot,2024-02,7.837,MWh,E533762 +M51,head_office,2024-09,10422,kWh,E612797 +M55,depot,2024-01,19154,kWh,E656188 +M39,depot,2024-07,19.167,MWh,E877749 +M51,head_office,2024-08,10.092,MWh,E396278 +M51,head_office,2024-02,11226,kWh,E812830 +M39,depot,2024-04,20752,kWh,E988528 +M55,depot,2024-11,17.169,MWh,E283318 +M44,depot,2024-01,9018,kWh,E280362 +M40,head_office,2024-12,39959,kWh,E766718 +M51,head_office,2024-04,9.525,MWh,E717144 +M39,depot,2024-03,20955,kWh,E475571 +M39,depot,2024-12,24311,kWh,E210812 +M41,workshop,2024-03,3.540,MWh,E305756 +M44,depot,2024-09,7383,kWh,E152260 +M55,depot,2024-11,17.169,MWh,E283318 +M55,depot,2024-03,19788,kWh,E441541 +M39,depot,2024-12,24311,kWh,E210812 +M41,workshop,2024-01,3389,kWh,E874468 +M40,head_office,2024-10,38477,kWh,E396060 +M39,depot,2024-05,18.833,MWh,E922331 +M40,head_office,2024-04,33.882,MWh,E490073 +M39,depot,2024-07,19.167,MWh,E877749 +M51,head_office,2024-05,9.554,MWh,E917999 +M44,depot,2024-08,7091,kWh,E950141 +M41,workshop,2024-01,3.389,MWh,E874468 +M40,head_office,2024-02,38.802,MWh,E761548 +M44,depot,2024-04,6522,kWh,E873295 +M51,head_office,2024-12,12.685,MWh,E845625 +M41,workshop,2024-04,2.970,MWh,E685823 +M40,head_office,2024-09,35.676,MWh,E888795 +M39,depot,2024-06,18.496,MWh,E512643 +M44,depot,2024-11,8167,kWh,E524859 +M40,head_office,2024-08,34409,kWh,E694527 +M55,depot,2024-09,15899,kWh,E714599 +M39,depot,2024-08,18523,kWh,E790564 +M41,workshop,2024-12,3647,kWh,E892184 +M51,head_office,2024-07,9.071,MWh,E397252 +M39,depot,2024-09,18460,kWh,E851009 +M44,depot,2024-05,7.507,MWh,E837712 +M41,workshop,2024-02,3.676,MWh,E302433 +M40,head_office,2024-11,33881,kWh,E600980 +M41,workshop,2024-04,2970,kWh,E685823 +M55,depot,2024-06,14347,kWh,E211145 +M51,head_office,2024-03,11620,kWh,E955497 +M41,workshop,2024-05,3.044,MWh,E336395 +M41,workshop,2024-07,2.843,MWh,E553227 +M41,workshop,2024-09,3230,kWh,E296874 +M39,depot,2024-10,21051,kWh,E764853 +M51,head_office,2024-11,12527,kWh,E651072 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..774367b626fd3f447a4e0c936b3b286953066ffe --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2024 monthly electricity consumption export for the meters of Harlow Fold Logistics (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee40283fa70b94616b2fce4be665761832854fe4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 45 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..aabe3adc0186e7dba4f86263f847a4c297040d14 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/checks.json @@ -0,0 +1,173 @@ +[ + { + "path": "meters.M39.annual_kwh", + "type": "number", + "value": 243862.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M39.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M40.annual_kwh", + "type": "number", + "value": 427551.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M40.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M41.annual_kwh", + "type": "number", + "value": 38303.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M41.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M44.annual_kwh", + "type": "number", + "value": 92699.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M44.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M51.annual_kwh", + "type": "number", + "value": 128227.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M51.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M55.annual_kwh", + "type": "number", + "value": 206549.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M55.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1137191.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 359.35, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M40.2024-03", + "type": "number", + "value": 36342.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M41.2024-06", + "type": "number", + "value": 2943.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M41.2024-10", + "type": "number", + "value": 3145.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M55.2024-02", + "type": "number", + "value": 19471.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M55.2024-07", + "type": "number", + "value": 14633.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M40", + "M41", + "M55" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.depot", + "type": "number", + "value": 171.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.head_office", + "type": "number", + "value": 175.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.workshop", + "type": "number", + "value": 12.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2024-12", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0045/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..175baef4e751384756eeac27141d2e5141922d11 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2021 electricity return + +- Electricity emission factor: 0.448 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..ab03c1554839c8675f81f1aae190ceb87e860581 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/environment/workdir/meter_readings.csv @@ -0,0 +1,76 @@ +meter_id,site,month,consumption,unit,invoice_ref +M53,warehouse,2021-12,34174,kWh,E725027 +M43,workshop,2021-04,6.621,MWh,E371315 +M42,warehouse,2021-09,7057,kWh,E730787 +M06,warehouse,2021-04,17930,kWh,E529946 +M43,workshop,2021-02,8020,kWh,E787729 +M06,warehouse,2021-05,19901,kWh,E749908 +M06,warehouse,2021-06,17.917,MWh,E550919 +M42,warehouse,2021-01,8.354,MWh,E640760 +M43,workshop,2021-03,7506,kWh,E554703 +M01,head_office,2021-08,9233,kWh,E260139 +M43,workshop,2021-06,6248,kWh,E346625 +M43,workshop,2021-08,6.256,MWh,E393813 +M29,workshop,2021-06,14647,kWh,E656401 +M43,workshop,2021-07,6606,kWh,E125805 +M53,warehouse,2021-05,26401,kWh,E419207 +M29,workshop,2021-05,15.175,MWh,E780612 +M53,warehouse,2021-11,27946,kWh,E350558 +M06,warehouse,2021-03,17975,kWh,E456650 +M29,workshop,2021-12,19446,kWh,E137883 +M43,workshop,2021-05,6.499,MWh,E753241 +M42,warehouse,2021-01,8.354,MWh,E640760 +M53,warehouse,2021-03,29113,kWh,E903027 +M53,warehouse,2021-10,26.993,MWh,E620084 +M29,workshop,2021-07,14.570,MWh,E325067 +M01,head_office,2021-01,10578,kWh,E967119 +M29,workshop,2021-02,17776,kWh,E370970 +M43,workshop,2021-11,8546,kWh,E840571 +M06,warehouse,2021-10,17851,kWh,E593089 +M42,warehouse,2021-11,8.359,MWh,E742368 +M29,workshop,2021-04,14489,kWh,E948133 +M06,warehouse,2021-01,18.973,MWh,E267111 +M01,head_office,2021-10,10306,kWh,E863251 +M06,warehouse,2021-06,17.917,MWh,E550919 +M01,head_office,2021-03,11062,kWh,E514148 +M06,warehouse,2021-07,16950,kWh,E825993 +M42,warehouse,2021-10,8.740,MWh,E365525 +M29,workshop,2021-11,19504,kWh,E497109 +M42,warehouse,2021-02,8561,kWh,E678723 +M53,warehouse,2021-02,32160,kWh,E224481 +M06,warehouse,2021-09,17821,kWh,E965769 +M06,warehouse,2021-02,20007,kWh,E533100 +M43,workshop,2021-10,7.157,MWh,E754851 +M42,warehouse,2021-12,8691,kWh,E858162 +M43,workshop,2021-06,6248,kWh,E346625 +M43,workshop,2021-07,6606,kWh,E125805 +M53,warehouse,2021-01,27391,kWh,E687626 +M42,warehouse,2021-12,8691,kWh,E858162 +M29,workshop,2021-09,15968,kWh,E804143 +M29,workshop,2021-10,16.719,MWh,E243091 +M01,head_office,2021-02,11613,kWh,E527645 +M42,warehouse,2021-05,7115,kWh,E222568 +M42,warehouse,2021-03,8047,kWh,E896627 +M29,workshop,2021-01,18.410,MWh,E216115 +M43,workshop,2021-01,8.731,MWh,E222141 +M01,head_office,2021-02,11613,kWh,E527645 +M53,warehouse,2021-09,29432,kWh,E131880 +M01,head_office,2021-12,13241,kWh,E712918 +M01,head_office,2021-05,10.072,MWh,E375309 +M01,head_office,2021-09,8958,kWh,E581694 +M42,warehouse,2021-06,6812,kWh,E572870 +M06,warehouse,2021-12,22.365,MWh,E180026 +M53,warehouse,2021-07,24797,kWh,E795692 +M06,warehouse,2021-08,18277,kWh,E680978 +M43,workshop,2021-12,9.009,MWh,E125267 +M01,head_office,2021-11,10.183,MWh,E284725 +M29,workshop,2021-03,14.912,MWh,E416256 +M01,head_office,2021-04,8774,kWh,E196597 +M01,head_office,2021-06,9471,kWh,E654087 +M29,workshop,2021-08,15428,kWh,E924766 +M43,workshop,2021-05,6499,kWh,E753241 +M42,warehouse,2021-02,8561,kWh,E678723 +M53,warehouse,2021-04,26850,kWh,E729416 +M42,warehouse,2021-07,7131,kWh,E598019 +M43,workshop,2021-09,6.714,MWh,E697803 +M01,head_office,2021-07,8005,kWh,E638156 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0b3d418fecc6c82f4f3cf73f4983d9ba0b2f8dc6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2021 monthly electricity consumption export for the meters of Brantholm Municipality (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..aa9e483ce958218da1b741aae946fd694751a991 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 57 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e76fb599f09a1f85cfa8dafde80663a9d0539792 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/checks.json @@ -0,0 +1,173 @@ +[ + { + "path": "meters.M01.annual_kwh", + "type": "number", + "value": 121496.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M01.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M06.annual_kwh", + "type": "number", + "value": 226075.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M06.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M29.annual_kwh", + "type": "number", + "value": 197044.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M29.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M42.annual_kwh", + "type": "number", + "value": 93542.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M42.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M43.annual_kwh", + "type": "number", + "value": 87913.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M43.duplicate_rows", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "meters.M53.annual_kwh", + "type": "number", + "value": 337970.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M53.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1064040.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 476.69, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M06.2021-11", + "type": "number", + "value": 20108.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M42.2021-04", + "type": "number", + "value": 7581.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M42.2021-08", + "type": "number", + "value": 7094.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M53.2021-06", + "type": "number", + "value": 25599.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M53.2021-08", + "type": "number", + "value": 27114.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M06", + "M42", + "M53" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.head_office", + "type": "number", + "value": 54.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.warehouse", + "type": "number", + "value": 294.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.workshop", + "type": "number", + "value": 127.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2021-12", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0057/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..44b1ee35c9771d8024c417313eafd3ab6726afcc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2020 electricity return + +- Electricity emission factor: 0.206 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..846ecf3aea4bc63b405dcbd6c5392eeb9e28710d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/environment/workdir/meter_readings.csv @@ -0,0 +1,74 @@ +meter_id,site,month,consumption,unit,invoice_ref +M42,warehouse,2020-12,26636,kWh,E805175 +M39,depot,2020-05,24936,kWh,E492138 +M27,workshop,2020-11,20.580,MWh,E848847 +M10,depot,2020-03,43358,kWh,E575549 +M39,depot,2020-08,24693,kWh,E486477 +M10,depot,2020-05,42297,kWh,E808002 +M39,depot,2020-04,23896,kWh,E889022 +M12,warehouse,2020-02,3620,kWh,E920726 +M12,warehouse,2020-04,2666,kWh,E334994 +M39,depot,2020-03,25.580,MWh,E814440 +M42,warehouse,2020-10,22.529,MWh,E814072 +M39,depot,2020-02,30055,kWh,E619361 +M36,workshop,2020-03,41.170,MWh,E428189 +M10,depot,2020-09,39745,kWh,E272830 +M39,depot,2020-01,27886,kWh,E229653 +M12,warehouse,2020-08,2815,kWh,E614096 +M27,workshop,2020-02,22313,kWh,E822842 +M42,warehouse,2020-04,23027,kWh,E307531 +M27,workshop,2020-09,19.993,MWh,E156544 +M27,workshop,2020-01,22830,kWh,E330016 +M42,warehouse,2020-11,28281,kWh,E487888 +M12,warehouse,2020-01,3245,kWh,E335500 +M36,workshop,2020-05,39.583,MWh,E765642 +M12,warehouse,2020-09,2789,kWh,E480951 +M27,workshop,2020-10,21.918,MWh,E488265 +M10,depot,2020-02,45183,kWh,E733574 +M42,warehouse,2020-10,22529,kWh,E814072 +M27,workshop,2020-12,23865,kWh,E929636 +M36,workshop,2020-01,48.624,MWh,E343996 +M12,warehouse,2020-12,3122,kWh,E402760 +M39,depot,2020-01,27.886,MWh,E229653 +M10,depot,2020-12,44.677,MWh,E125543 +M12,warehouse,2020-11,2992,kWh,E217694 +M42,warehouse,2020-08,22.229,MWh,E729440 +M36,workshop,2020-02,42.827,MWh,E188938 +M27,workshop,2020-07,16.221,MWh,E297826 +M39,depot,2020-12,35389,kWh,E168579 +M12,warehouse,2020-07,2.755,MWh,E649576 +M27,workshop,2020-04,19.570,MWh,E567451 +M36,workshop,2020-06,40459,kWh,E783263 +M36,workshop,2020-08,38526,kWh,E551078 +M10,depot,2020-09,39745,kWh,E272830 +M12,warehouse,2020-10,3123,kWh,E366079 +M36,workshop,2020-04,40613,kWh,E366033 +M10,depot,2020-02,45183,kWh,E733574 +M12,warehouse,2020-06,2.438,MWh,E540956 +M39,depot,2020-11,31181,kWh,E962025 +M39,depot,2020-06,24.420,MWh,E966101 +M39,depot,2020-07,21923,kWh,E657998 +M36,workshop,2020-02,42827,kWh,E188938 +M42,warehouse,2020-06,22.020,MWh,E540322 +M42,warehouse,2020-05,19874,kWh,E866048 +M36,workshop,2020-11,45156,kWh,E623089 +M10,depot,2020-08,37860,kWh,E627896 +M42,warehouse,2020-01,25.976,MWh,E946123 +M10,depot,2020-11,41.266,MWh,E960372 +M10,depot,2020-07,36541,kWh,E669486 +M27,workshop,2020-08,17.964,MWh,E296396 +M42,warehouse,2020-09,22397,kWh,E947584 +M27,workshop,2020-06,17910,kWh,E573607 +M39,depot,2020-09,24772,kWh,E649692 +M36,workshop,2020-09,36964,kWh,E356889 +M10,depot,2020-01,45388,kWh,E484040 +M27,workshop,2020-05,16958,kWh,E145857 +M36,workshop,2020-12,51549,kWh,E504029 +M42,warehouse,2020-03,24011,kWh,E487391 +M36,workshop,2020-07,37051,kWh,E147695 +M39,depot,2020-10,27.248,MWh,E651788 +M10,depot,2020-04,36.096,MWh,E422479 +M27,workshop,2020-03,20969,kWh,E419283 +M12,warehouse,2020-08,2.815,MWh,E614096 +M42,warehouse,2020-07,18893,kWh,E373462 +M42,warehouse,2020-02,25719,kWh,E442625 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1cc5683c7b3011110371c883ce85963a7fe8f507 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2020 monthly electricity consumption export for the meters of Harlow Fold Logistics (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..be32a0144f2641760c7b6b166cd858ddd4ed2aac --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 69 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8f7072d10004515a12f5ddcc4f9c498ab8231498 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/checks.json @@ -0,0 +1,173 @@ +[ + { + "path": "meters.M10.annual_kwh", + "type": "number", + "value": 492335.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M10.duplicate_rows", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "meters.M12.annual_kwh", + "type": "number", + "value": 35260.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M12.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M27.annual_kwh", + "type": "number", + "value": 241091.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M27.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M36.annual_kwh", + "type": "number", + "value": 503582.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M36.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M39.annual_kwh", + "type": "number", + "value": 321979.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M39.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M42.annual_kwh", + "type": "number", + "value": 281592.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M42.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1875839.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 386.42, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M10.2020-06", + "type": "number", + "value": 39419.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M10.2020-10", + "type": "number", + "value": 40505.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M12.2020-03", + "type": "number", + "value": 3143.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M12.2020-05", + "type": "number", + "value": 2552.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M36.2020-10", + "type": "number", + "value": 41060.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M10", + "M12", + "M36" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.depot", + "type": "number", + "value": 167.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.warehouse", + "type": "number", + "value": 65.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.workshop", + "type": "number", + "value": 153.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2020-12", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0069/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/workdir/data_rules.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/workdir/data_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..72ae02b3aec0d459cd820c91256731aaf8ccc2b9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/workdir/data_rules.md @@ -0,0 +1,8 @@ +# Data rules for the 2020 electricity return + +- Electricity emission factor: 0.244 kg CO2e per kWh (use this value). + +1. The `consumption` column mixes units: each row is in kWh or in MWh as its `unit` says. Convert everything to kWh first (1 MWh = 1000 kWh). +2. A meter should have exactly one row per month. Where a meter has more than one row for the same month, the later rows are duplicates loaded twice: they always carry the same consumption as the first once both are in the same unit. Keep one row and drop the rest. +3. Where a meter has no row for a month, fill it with the mean of that meter's consumption in the month before and the month after. A missing month always has both neighbours present, and it is never January or December. +4. Emissions = cleaned consumption in kWh x the electricity emission factor, converted from kg to tonnes (1 tonne = 1000 kg). diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/workdir/meter_readings.csv b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/workdir/meter_readings.csv new file mode 100644 index 0000000000000000000000000000000000000000..fb7646eb55c91c1f3929434c66cfba065d64dc89 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/environment/workdir/meter_readings.csv @@ -0,0 +1,72 @@ +meter_id,site,month,consumption,unit,invoice_ref +M06,head_office,2020-07,23.341,MWh,E490977 +M06,head_office,2020-02,30101,kWh,E823333 +M06,head_office,2020-05,23.931,MWh,E623636 +M15,warehouse,2020-06,7970,kWh,E110487 +M15,warehouse,2020-12,9312,kWh,E945520 +M50,warehouse,2020-10,44934,kWh,E409096 +M06,head_office,2020-03,31165,kWh,E277366 +M22,workshop,2020-11,21.377,MWh,E734763 +M50,warehouse,2020-12,42792,kWh,E886800 +M15,warehouse,2020-02,10941,kWh,E200497 +M41,head_office,2020-10,19.437,MWh,E257717 +M15,warehouse,2020-10,9362,kWh,E173491 +M41,head_office,2020-11,22458,kWh,E492573 +M39,warehouse,2020-05,45119,kWh,E467529 +M06,head_office,2020-09,25672,kWh,E626047 +M39,warehouse,2020-04,44281,kWh,E722310 +M41,head_office,2020-04,20081,kWh,E702072 +M39,warehouse,2020-06,39799,kWh,E966395 +M22,workshop,2020-05,15.990,MWh,E634987 +M15,warehouse,2020-09,8.808,MWh,E406429 +M22,workshop,2020-07,17.330,MWh,E364486 +M41,head_office,2020-07,16.711,MWh,E707683 +M22,workshop,2020-01,20178,kWh,E443108 +M41,head_office,2020-08,16801,kWh,E297558 +M06,head_office,2020-12,33073,kWh,E921728 +M41,head_office,2020-05,19748,kWh,E980398 +M22,workshop,2020-09,18132,kWh,E480701 +M50,warehouse,2020-05,42987,kWh,E888116 +M50,warehouse,2020-06,40.318,MWh,E447713 +M41,head_office,2020-01,22822,kWh,E643211 +M22,workshop,2020-06,15819,kWh,E949573 +M39,warehouse,2020-08,43271,kWh,E694167 +M15,warehouse,2020-11,8805,kWh,E555825 +M15,warehouse,2020-05,8040,kWh,E937424 +M41,head_office,2020-03,19703,kWh,E441443 +M15,warehouse,2020-07,7.858,MWh,E793313 +M22,workshop,2020-03,20194,kWh,E915172 +M39,warehouse,2020-01,55.493,MWh,E920643 +M50,warehouse,2020-09,43.980,MWh,E601802 +M39,warehouse,2020-09,43.397,MWh,E516407 +M15,warehouse,2020-03,8871,kWh,E265411 +M50,warehouse,2020-08,43613,kWh,E880950 +M41,head_office,2020-12,20.981,MWh,E899331 +M39,warehouse,2020-10,44251,kWh,E264063 +M41,head_office,2020-06,16351,kWh,E629457 +M50,warehouse,2020-07,41817,kWh,E325092 +M06,head_office,2020-01,33714,kWh,E775176 +M41,head_office,2020-11,22458,kWh,E492573 +M39,warehouse,2020-02,45619,kWh,E295552 +M41,head_office,2020-09,17344,kWh,E570289 +M39,warehouse,2020-12,49.571,MWh,E359837 +M22,workshop,2020-12,21684,kWh,E327082 +M06,head_office,2020-10,29230,kWh,E862429 +M50,warehouse,2020-04,41.660,MWh,E102014 +M50,warehouse,2020-01,55.146,MWh,E638368 +M39,warehouse,2020-07,41640,kWh,E989213 +M50,warehouse,2020-03,47762,kWh,E163724 +M39,warehouse,2020-11,50705,kWh,E833274 +M15,warehouse,2020-04,8193,kWh,E565327 +M50,warehouse,2020-02,45207,kWh,E479805 +M41,head_office,2020-02,21119,kWh,E954129 +M39,warehouse,2020-03,47.391,MWh,E949400 +M06,head_office,2020-08,23309,kWh,E591637 +M22,workshop,2020-04,18011,kWh,E125605 +M06,head_office,2020-04,27847,kWh,E734367 +M15,warehouse,2020-01,10.247,MWh,E553359 +M06,head_office,2020-06,22088,kWh,E771947 +M50,warehouse,2020-11,42705,kWh,E739623 +M06,head_office,2020-07,23341,kWh,E490977 +M22,workshop,2020-10,18083,kWh,E332541 +M22,workshop,2020-12,21684,kWh,E327082 diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/instruction.md b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f9d9306e2c64343a0e867dc40a7990d2c1fcb427 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: cleaning the meter data + +`meter_readings.csv` is the 2020 monthly electricity consumption export for the meters of Tarnwick Borough Council (a synthetic organisation). It was assembled from several uploads and needs cleaning before it can be used. `data_rules.md` gives the cleaning rules and the emission factor. + +Write `answer.json` in this folder, a JSON object with: + +- `meters`: an object keyed by meter id, each with + - `annual_kwh`: the meter's consumption for the twelve months after cleaning, in kWh, 1 decimal. + - `duplicate_rows`: how many of its rows you dropped as duplicates, as an integer (0 if none). +- `duplicate_rows_removed`: the number of duplicate rows dropped over all meters, as an integer. +- `total_kwh`: cleaned consumption of all meters, in kWh, 1 decimal. +- `total_t_co2e`: emissions from `total_kwh`, in tonnes CO2e, 2 decimals. +- `filled`: an object keyed by meter id, only for meters that had a missing month. Each value is an object keyed by the missing month (`YYYY-MM`) giving the filled consumption in kWh, 1 decimal. +- `meters_with_gap`: list of the meter ids that had at least one missing month (any order). +- `by_site_t_co2e`: an object keyed by site, tonnes CO2e from the cleaned consumption of that site's meters, 2 decimals. +- `peak_month`: the month (`YYYY-MM`) with the highest cleaned consumption summed over all meters. + +Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/task.toml b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bce313c9e90fcbfa62b65c775ee419dfc1626db2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "data-quality", "isced-0521", "train"] +isced_f = "0521" +family = "data-quality" +split = "train" +seed = 81 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f1a8f5725c476418df397460a81a420392b8b8e9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/checks.json @@ -0,0 +1,166 @@ +[ + { + "path": "meters.M06.annual_kwh", + "type": "number", + "value": 334622.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M06.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M15.annual_kwh", + "type": "number", + "value": 106740.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M15.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M22.annual_kwh", + "type": "number", + "value": 224715.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M22.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M39.annual_kwh", + "type": "number", + "value": 550537.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M39.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "meters.M41.annual_kwh", + "type": "number", + "value": 233556.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M41.duplicate_rows", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "meters.M50.annual_kwh", + "type": "number", + "value": 532921.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters.M50.duplicate_rows", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "duplicate_rows_removed", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "total_kwh", + "type": "number", + "value": 1983091.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "total_t_co2e", + "type": "number", + "value": 483.87, + "abs_tol": 0.01, + "weight": 2 + }, + { + "path": "filled.M06.2020-11", + "type": "number", + "value": 31151.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M15.2020-08", + "type": "number", + "value": 8333.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M22.2020-02", + "type": "number", + "value": 20186.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "filled.M22.2020-08", + "type": "number", + "value": 17731.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "meters_with_gap", + "type": "set", + "value": [ + "M06", + "M15", + "M22" + ], + "item": "str", + "weight": 2 + }, + { + "path": "by_site_t_co2e.head_office", + "type": "number", + "value": 138.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.warehouse", + "type": "number", + "value": 290.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "by_site_t_co2e.workshop", + "type": "number", + "value": 54.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "peak_month", + "type": "str", + "value": "2020-01", + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-data-quality-d3-t0081/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..bad9858795e0c63b27f569b9fdcbfbefb372f7ba --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.76,0.132,0.15 +petrol_combustion,litre,2.33,0.812,0.224 +heating_oil_boiler,litre,2.58,0.346,0.0185 +natural_gas_boiler,m3,2.0,0.206,0.0309 +wood_chip_boiler,tonne,0.0,268.0,42.7 +landfilled_waste,tonne,0.0,60400.0,0.0 +dairy_cattle,head,0.0,137000.0,1050.0 +nitrogen_fertiliser,tonne,0.0,0.0,12700.0 +wastewater_treatment,person,0.0,470.0,72.9 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..8fdfb883c35383d9c7b6876ae9d2fa894c920711 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,dairy_cattle,dairy cows kept over the year,513,head +E02,petrol_combustion,petrol for pool cars,6832.5,litre +E03,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),697.1,tonne +E04,heating_oil_boiler,heating oil burned in boilers,19794.8,litre diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c4ede7c0f3f1b71fd8db21b4be14f30accb249c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2019 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..39770d0df6fb0b50e303b4a007d3b4ec1cd0a0a6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "eval"] +isced_f = "0521" +family = "multi-gas" +split = "eval" +seed = 10002 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e9f8001d2ff66ad59a931a1e0fe5a59dfd48c328 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 70281.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 538.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 1917.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 15.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 5.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 1.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 16.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 186.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 29.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 13.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 51.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 6.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 0.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 51.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 66.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 1762.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 169.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 1998.95, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0002/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..91a2cde1ccbe2010822a24b08a7ab9d666de660e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.81,0.0882,0.16 +petrol_combustion,litre,2.35,0.704,0.228 +heating_oil_boiler,litre,2.57,0.332,0.0227 +natural_gas_boiler,m3,2.08,0.196,0.0329 +wood_chip_boiler,tonne,0.0,257.0,40.9 +landfilled_waste,tonne,0.0,51700.0,0.0 +dairy_cattle,head,0.0,112000.0,1130.0 +nitrogen_fertiliser,tonne,0.0,0.0,12700.0 +wastewater_treatment,person,0.0,379.0,50.3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..a0d7d5ca412ac307f4d7cf2dd467bc5272d4df9b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,heating_oil_boiler,heating oil burned in boilers,34767,litre +E02,petrol_combustion,petrol for pool cars,6325.8,litre +E03,landfilled_waste,municipal waste sent to landfill,3676.9,tonne +E04,dairy_cattle,dairy cows kept over the year,547,head diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..963802301e8f5ba57ed3360da1294cf5a3cbacc0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e0d7fba079ded8471b77e6c70f249b90f28d8924 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "eval"] +isced_f = "0521" +family = "multi-gas" +split = "eval" +seed = 10014 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..26080aad1cf10d0144cfb5b3803a75d77f887325 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 89.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 11.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 89.88, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 14.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 4.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 1.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 15.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 190095.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 5322.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 61264.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 618.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 1879.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 104.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 7038.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 164.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 7307.13, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-e0014/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..6b2cbcfb1abb828e5cebfd43cdc725ad38baebf8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.77,0.118,0.151 +petrol_combustion,litre,2.28,0.894,0.265 +heating_oil_boiler,litre,2.59,0.309,0.0246 +natural_gas_boiler,m3,2.06,0.212,0.0348 +wood_chip_boiler,tonne,0.0,332.0,40.3 +landfilled_waste,tonne,0.0,43600.0,0.0 +dairy_cattle,head,0.0,113000.0,971.0 +nitrogen_fertiliser,tonne,0.0,0.0,17500.0 +wastewater_treatment,person,0.0,393.0,63.2 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..a1cadea5a95b2027283c811f45bd52a28086971b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,20.1,tonne +E02,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,29.4,tonne +E03,heating_oil_boiler,heating oil burned in boilers,4333.4,litre +E04,natural_gas_boiler,natural gas burned in boilers,187209,m3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..60873cac5e026ed2c5187f49468f0d13de79c887 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Brantholm Municipality (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..932bf10d1643f68b8612638b7ee806f1eb407abe --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 2 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8c868e35044d722a739943981b594b13d76d665d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 351.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 93.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 514.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 136.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 11.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 1.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 0.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 11.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 385.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 39.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 6.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 388.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 396.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 1.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 231.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 629.33, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0002/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..ad3a43416d4ac18028f733542c8a9cee23f1b079 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.7,0.112,0.168 +petrol_combustion,litre,2.26,0.818,0.281 +heating_oil_boiler,litre,2.45,0.285,0.0201 +natural_gas_boiler,m3,1.98,0.181,0.0391 +wood_chip_boiler,tonne,0.0,335.0,44.0 +landfilled_waste,tonne,0.0,56500.0,0.0 +dairy_cattle,head,0.0,134000.0,1120.0 +nitrogen_fertiliser,tonne,0.0,0.0,15600.0 +wastewater_treatment,person,0.0,367.0,56.3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..8594336baa78ead62fc875574c1ba28b79d89078 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,8.1,tonne +E02,diesel_combustion,diesel for vehicles and plant,40068.2,litre +E03,diesel_combustion,diesel for vehicles and plant,52441.3,litre +E04,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),590.9,tonne diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..963802301e8f5ba57ed3360da1294cf5a3cbacc0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..52384e43855d4168ef204d4c2296d98160ee4700 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 14 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..617a8c93cca69ab2ef5da85ec5b45fd7e71527f7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 126.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 37.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 108.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 4.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 6.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 110.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 141.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 5.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 8.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 144.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 197.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 26.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 12.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 249.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 5.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 50.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 305.02, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0014/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..e2443a5250fc65a6cd5e3ba0fa66e1cf39813c4c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.77,0.0977,0.136 +petrol_combustion,litre,2.27,0.834,0.259 +heating_oil_boiler,litre,2.54,0.294,0.0178 +natural_gas_boiler,m3,2.09,0.221,0.0354 +wood_chip_boiler,tonne,0.0,344.0,44.9 +landfilled_waste,tonne,0.0,46600.0,0.0 +dairy_cattle,head,0.0,137000.0,802.0 +nitrogen_fertiliser,tonne,0.0,0.0,16700.0 +wastewater_treatment,person,0.0,487.0,71.3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..73b20fd9846ce0c013061879d7a020c86e09d099 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),762.7,tonne +E02,heating_oil_boiler,heating oil burned in boilers,24081.8,litre +E03,petrol_combustion,petrol for pool cars,8739.5,litre +E04,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),506.4,tonne diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbb088b1fd295a01029cbf718b69d63c1a4b46b7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Lindqvist Castings (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9c48e7c4cce581474b0a56c043b1b3288c18c8ac --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 26 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1ebb2453471bca4400469ea7656a6590cec45d1e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 262.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 34.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 16.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 61.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 7.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 0.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 61.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 19.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 7.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 2.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 20.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 174.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 22.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 10.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 81.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 12.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 15.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 109.45, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0026/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..a6a16287776874830f11fa5212f45d7804e4c089 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.57,0.13,0.148 +petrol_combustion,litre,2.36,0.856,0.244 +heating_oil_boiler,litre,2.63,0.3,0.0207 +natural_gas_boiler,m3,2.03,0.226,0.041 +wood_chip_boiler,tonne,0.0,313.0,36.7 +landfilled_waste,tonne,0.0,56800.0,0.0 +dairy_cattle,head,0.0,150000.0,821.0 +nitrogen_fertiliser,tonne,0.0,0.0,15300.0 +wastewater_treatment,person,0.0,418.0,74.0 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..e8cff596f0dbb56d47c2c19ba278efd7c8866d60 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,landfilled_waste,municipal waste sent to landfill,2505.4,tonne +E02,petrol_combustion,petrol for pool cars,6161,litre +E03,petrol_combustion,petrol for pool cars,7518.5,litre +E04,landfilled_waste,municipal waste sent to landfill,287.2,tonne diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8daa7dd90ba29930bc06276dcb87d95f7c41214d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2022 greenhouse-gas inventory for Vessby Dairy Cooperative (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..149227c066182b811bff91b7e37ea9ed7150328d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 38 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c7f7df070f57f9a259ff9c39e883ecd6fc7fc3d8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 142306.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 3557.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 14.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 5.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 1.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 15.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 17.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 6.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 1.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 18.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 16312.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 407.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 32.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 3965.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 0.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 3999.06, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0038/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..e5c86d6855b859de98bc233f39f56d4528e9d0b5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.76,0.0931,0.125 +petrol_combustion,litre,2.31,0.794,0.221 +heating_oil_boiler,litre,2.49,0.312,0.0172 +natural_gas_boiler,m3,2.05,0.163,0.0324 +wood_chip_boiler,tonne,0.0,296.0,35.6 +landfilled_waste,tonne,0.0,48400.0,0.0 +dairy_cattle,head,0.0,138000.0,1050.0 +nitrogen_fertiliser,tonne,0.0,0.0,15200.0 +wastewater_treatment,person,0.0,469.0,72.8 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..3bafd961da9f5fbb3ad7791bdeb3a7dd13645d30 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,natural_gas_boiler,natural gas burned in boilers,118540,m3 +E02,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,65.4,tonne +E03,dairy_cattle,dairy cows kept over the year,484,head +E04,diesel_combustion,diesel for vehicles and plant,20288.8,litre diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d331de82e83b1a70413532454a525d2cfd8a5c8f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2022 greenhouse-gas inventory for Lindqvist Castings (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dae34ce3ccac9ec8904a0630a53cc970730c4e50 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 50 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2f3a84323a53726b96a9153824e175617e028e34 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 243.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 19.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 3.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 244.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 994.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 296.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 66792.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 508.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 1821.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 56.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 1.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 2.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 56.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 299.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 1670.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 449.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 2418.91, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0050/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..b6abd03dbdada6addf80f0c8f23d0557da3031eb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.7,0.109,0.113 +petrol_combustion,litre,2.36,0.913,0.258 +heating_oil_boiler,litre,2.54,0.372,0.0199 +natural_gas_boiler,m3,2.04,0.202,0.0324 +wood_chip_boiler,tonne,0.0,356.0,43.3 +landfilled_waste,tonne,0.0,54300.0,0.0 +dairy_cattle,head,0.0,117000.0,1100.0 +nitrogen_fertiliser,tonne,0.0,0.0,15700.0 +wastewater_treatment,person,0.0,371.0,72.6 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..dfe54ab7d4f8ccf943e3b5d046e9e35b099702c3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,dairy_cattle,dairy cows kept over the year,112,head +E02,natural_gas_boiler,natural gas burned in boilers,181975,m3 +E03,petrol_combustion,petrol for pool cars,10690.5,litre +E04,diesel_combustion,diesel for vehicles and plant,18027.7,litre diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8daa7dd90ba29930bc06276dcb87d95f7c41214d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2022 greenhouse-gas inventory for Vessby Dairy Cooperative (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5c5a4eafeba8a4f77477c53f73498c8cc379b489 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 62 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a2da4a57a1f6e764531bf4051a3287f8daef260c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 13104.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 123.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 364.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 371.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 36.76, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 5.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 373.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 25.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 9.76, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 2.76, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 26.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 48.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 1.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 2.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 49.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 445.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 328.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 39.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 813.85, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0062/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..35ac40d32f48b2c02e0183f6167c4b1fc1cdbae5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.67,0.127,0.138 +petrol_combustion,litre,2.32,0.659,0.262 +heating_oil_boiler,litre,2.5,0.349,0.0202 +natural_gas_boiler,m3,2.02,0.192,0.0377 +wood_chip_boiler,tonne,0.0,268.0,42.4 +landfilled_waste,tonne,0.0,49400.0,0.0 +dairy_cattle,head,0.0,108000.0,954.0 +nitrogen_fertiliser,tonne,0.0,0.0,16000.0 +wastewater_treatment,person,0.0,476.0,55.0 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..9121bca16a984e59bb175fe4b49cf3dc65b8f6e9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/environment/workdir/sources.csv @@ -0,0 +1,5 @@ +source_id,category,description,amount,unit +E01,petrol_combustion,petrol for pool cars,5443.1,litre +E02,petrol_combustion,petrol for pool cars,17898.2,litre +E03,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,11.1,tonne +E04,dairy_cattle,dairy cows kept over the year,308,head diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..abdcc62d0ef29af3f31c09dd76d6e4f6c430d3da --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Vessby Dairy Cooperative (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Every amount is already in the unit of its category's factors. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..399987f832adfbd4ae8be5b6e4ac18aa74d508db --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 74 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f43afb2e3f78b71f903b3593d07d537112bdd65d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 12.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 3.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 1.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 13.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 41.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 11.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 4.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 43.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 177.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 52.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 33264.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 293.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 919.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 54.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 831.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 142.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 1028.45, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d1-t0074/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..a97cacdce95e288cd6b4675a5d6454be0278d550 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.66,0.0887,0.154 +petrol_combustion,litre,2.24,0.692,0.233 +heating_oil_boiler,litre,2.6,0.32,0.0226 +natural_gas_boiler,m3,1.99,0.164,0.0403 +wood_chip_boiler,tonne,0.0,289.0,48.4 +landfilled_waste,tonne,0.0,60800.0,0.0 +dairy_cattle,head,0.0,136000.0,1020.0 +nitrogen_fertiliser,tonne,0.0,0.0,15800.0 +wastewater_treatment,person,0.0,489.0,49.8 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..4a91588118cd1fdef6c8e2e8a548b0777ba35349 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,landfilled_waste,municipal waste sent to landfill,3295.6,tonne +E02,natural_gas_boiler,natural gas burned in boilers,172326,m3 +E03,landfilled_waste,municipal waste sent to landfill,306011,kg +E04,natural_gas_boiler,natural gas burned in boilers,31772,m3 +E05,wastewater_treatment,people connected to the treatment works,12699,person +E06,natural_gas_boiler,natural gas burned in boilers,48975,m3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..036fe6ee29c56b11805db28609c708b2718870cb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2019 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8eda345cfc1d105edea5ea38cc66658da4c5ebac --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "eval"] +isced_f = "0521" +family = "multi-gas" +split = "eval" +seed = 10006 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..99c452eb17bc26db8f326e467591fe0cb95d29a7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 200372.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 5610.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 342.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 28.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 6.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 345.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 18605.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 520.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 63.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 5.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 1.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 63.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 6209.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 632.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 341.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 97.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 8.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 1.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 98.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 503.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 6306.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 170.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 6980.33, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0006/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..daf712b8947a9f376c6f615f6249a887691fe109 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.76,0.11,0.163 +petrol_combustion,litre,2.38,0.669,0.238 +heating_oil_boiler,litre,2.47,0.321,0.0175 +natural_gas_boiler,m3,1.96,0.155,0.0349 +wood_chip_boiler,tonne,0.0,281.0,46.8 +landfilled_waste,tonne,0.0,57700.0,0.0 +dairy_cattle,head,0.0,103000.0,811.0 +nitrogen_fertiliser,tonne,0.0,0.0,13500.0 +wastewater_treatment,person,0.0,345.0,57.9 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..ab0e15230e84d0bd718094dec728e5024bc51f51 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,dairy_cattle,dairy cows kept over the year,41,head +E02,petrol_combustion,petrol for pool cars,2424.7,litre +E03,heating_oil_boiler,heating oil burned in boilers,25.611,m3 +E04,petrol_combustion,petrol for pool cars,5969.5,litre +E05,natural_gas_boiler,natural gas burned in boilers,71120,m3 +E06,petrol_combustion,petrol for pool cars,14924.9,litre diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..19163d62bac69bdecf960dbce43287324be2e032 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2019 greenhouse-gas inventory for Lindqvist Castings (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..342ffdc6546505757d848ef85a1225e7812ed58d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "eval"] +isced_f = "0521" +family = "multi-gas" +split = "eval" +seed = 10018 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2e07557cdbaa832fe6c84504ab34d3d3e6806af8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 4223.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 33.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 115.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 5.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 1.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 0.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 5.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 63.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 8.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 0.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 63.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 14.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 3.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 1.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 14.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 139.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 11.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 2.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 140.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 35.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 9.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 3.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 36.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 258.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 106.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 12.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 377.04, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-e0018/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..9fcac0e949d80f48a7b580a58120bbbb0d46450c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.76,0.129,0.162 +petrol_combustion,litre,2.26,0.705,0.234 +heating_oil_boiler,litre,2.56,0.301,0.0234 +natural_gas_boiler,m3,2.07,0.178,0.0291 +wood_chip_boiler,tonne,0.0,267.0,48.0 +landfilled_waste,tonne,0.0,49300.0,0.0 +dairy_cattle,head,0.0,117000.0,1040.0 +nitrogen_fertiliser,tonne,0.0,0.0,16300.0 +wastewater_treatment,person,0.0,333.0,70.5 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..78ffa35be2a9d30966ec02e2580ded84b46dfe3a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,wastewater_treatment,people connected to the treatment works,12935,person +E02,diesel_combustion,diesel for vehicles and plant,5744.3,litre +E03,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,50.4,tonne +E04,petrol_combustion,petrol for pool cars,16977.7,litre +E05,heating_oil_boiler,heating oil burned in boilers,17.657,m3 +E06,wastewater_treatment,people connected to the treatment works,28237,person diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85bdb435845e9c00a0fcd70ed08f76f90d8dd289 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2023 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b071e762f71385d33b2a371749bb53e7cca761a4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 6 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ea8905cd55744440bcde33891e61cdd8edc0eab7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 4307.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 911.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 362.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 15.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 0.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 0.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 16.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 821.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 217.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 38.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 11.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 3.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 39.76, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 45.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 5.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 0.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 45.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 9402.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 1990.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 790.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 99.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 384.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 988.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 1472.13, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0006/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..9d4ad2ce1a4e5cc3684bfd555c6fdc23b809898a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.81,0.13,0.123 +petrol_combustion,litre,2.31,0.768,0.204 +heating_oil_boiler,litre,2.6,0.329,0.0193 +natural_gas_boiler,m3,1.92,0.198,0.0377 +wood_chip_boiler,tonne,0.0,259.0,36.9 +landfilled_waste,tonne,0.0,59400.0,0.0 +dairy_cattle,head,0.0,117000.0,1130.0 +nitrogen_fertiliser,tonne,0.0,0.0,14300.0 +wastewater_treatment,person,0.0,463.0,59.6 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..ef616bf66d8c6c12d6911288792ba7b78c329cf6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,natural_gas_boiler,natural gas burned in boilers,144233,m3 +E02,petrol_combustion,petrol for pool cars,9116.7,litre +E03,landfilled_waste,municipal waste sent to landfill,1815.1,tonne +E04,natural_gas_boiler,natural gas burned in boilers,196140,m3 +E05,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),520.1,tonne +E06,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,66.1,tonne diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbb832a857a23682c7232990f6e9ef2d693c9f16 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2020 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b47ae4136ebea79679f6ffae6b8e9d7cbb9e2553 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 18 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..41cb61c70bd892ed0e8411e6b225f1776317c3ca --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 276.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 28.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 5.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 279.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 21.06, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 7.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 1.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 21.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 107816.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 3018.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 376.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 38.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 7.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 379.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 134.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 19.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 8.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 945.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 250.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 674.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 3024.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 259.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 3958.77, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0018/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..3ae138392cc45fecebc125e0bb587289659081a5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.78,0.099,0.114 +petrol_combustion,litre,2.39,0.659,0.274 +heating_oil_boiler,litre,2.52,0.322,0.0208 +natural_gas_boiler,m3,1.97,0.179,0.0417 +wood_chip_boiler,tonne,0.0,331.0,34.8 +landfilled_waste,tonne,0.0,59300.0,0.0 +dairy_cattle,head,0.0,110000.0,1080.0 +nitrogen_fertiliser,tonne,0.0,0.0,17100.0 +wastewater_treatment,person,0.0,414.0,51.7 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..eb53f03656d86c5789f71d2ba4862e1ed9ca44c1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,diesel_combustion,diesel for vehicles and plant,11.735,m3 +E02,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),753077,kg +E03,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,59.4,tonne +E04,diesel_combustion,diesel for vehicles and plant,23.729,m3 +E05,diesel_combustion,diesel for vehicles and plant,59.882,m3 +E06,dairy_cattle,dairy cows kept over the year,210,head diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3466aba346b7437c33e279ade9517244edfc00bc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2021 greenhouse-gas inventory for Marrow Vale Housing (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..975677420985652d25231a016f31680d68405a7b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 30 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6b1fcf9d38e48a71a55dc175140c602d497f9152 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 32.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 1.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 1.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 33.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 249.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 26.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 14.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 1015.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 302.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 65.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 2.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 2.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 66.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 166.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 5.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 6.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 168.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 23100.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 226.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 645.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 265.06, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 583.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 381.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 1230.36, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0030/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..6c985101205ae68c20b2c81d70e2015090592491 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.64,0.106,0.144 +petrol_combustion,litre,2.33,0.807,0.293 +heating_oil_boiler,litre,2.55,0.353,0.0183 +natural_gas_boiler,m3,2.03,0.206,0.0425 +wood_chip_boiler,tonne,0.0,254.0,45.4 +landfilled_waste,tonne,0.0,51600.0,0.0 +dairy_cattle,head,0.0,139000.0,812.0 +nitrogen_fertiliser,tonne,0.0,0.0,13800.0 +wastewater_treatment,person,0.0,383.0,73.6 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..a286c0880fbcb413b41f9043f9944ab7e9cc8107 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,heating_oil_boiler,heating oil burned in boilers,7.595,m3 +E02,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,69.3,tonne +E03,petrol_combustion,petrol for pool cars,5848.2,litre +E04,natural_gas_boiler,natural gas burned in boilers,153755,m3 +E05,natural_gas_boiler,natural gas burned in boilers,122642,m3 +E06,landfilled_waste,municipal waste sent to landfill,2102576,kg diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbb832a857a23682c7232990f6e9ef2d693c9f16 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2020 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8d0ec10516f0254ae4c6f03cffc23019a17b541d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 42 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..251a65e4ee7334d56ad163d4f53b62f88f441f92 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 19.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 2.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 19.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 956.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 284.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 13.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 4.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 1.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 14.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 312.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 31.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 6.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 314.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 248.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 25.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 5.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 251.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 108492.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 2712.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 594.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 2713.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 289.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 3597.05, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0042/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..0548c0066f869832d02363c67f2cdd2ba6104dd3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.77,0.103,0.113 +petrol_combustion,litre,2.34,0.846,0.299 +heating_oil_boiler,litre,2.54,0.323,0.0197 +natural_gas_boiler,m3,2.11,0.155,0.0325 +wood_chip_boiler,tonne,0.0,371.0,41.2 +landfilled_waste,tonne,0.0,52400.0,0.0 +dairy_cattle,head,0.0,114000.0,1050.0 +nitrogen_fertiliser,tonne,0.0,0.0,15900.0 +wastewater_treatment,person,0.0,405.0,50.5 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..0ed5daf6643cb584f2a77150093879ee3cf8f3cf --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,landfilled_waste,municipal waste sent to landfill,1383,tonne +E02,dairy_cattle,dairy cows kept over the year,567,head +E03,dairy_cattle,dairy cows kept over the year,310,head +E04,wastewater_treatment,people connected to the treatment works,14867,person +E05,petrol_combustion,petrol for pool cars,19526.6,litre +E06,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),253996,kg diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ec42a5708caa75180564120c195f3f7c81aa81f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2022 greenhouse-gas inventory for Lindqvist Castings (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c0084ccf63a933f88d11ee40a439d32b191ef57 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 54 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..457ca9165a7e825abda6f36927ea73fff977bb89 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 72469.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 1811.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 64638.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 595.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 1793.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 35340.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 325.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 980.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 6021.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 750.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 374.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 45.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 16.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 5.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 47.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 94.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 10.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 5.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 45.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 4464.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 503.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 5013.17, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0054/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..e4a348c5af65915ef95ffcaa7cc4895f19f39c0a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.81,0.113,0.152 +petrol_combustion,litre,2.32,0.679,0.288 +heating_oil_boiler,litre,2.56,0.365,0.0172 +natural_gas_boiler,m3,1.94,0.211,0.0308 +wood_chip_boiler,tonne,0.0,262.0,41.3 +landfilled_waste,tonne,0.0,54000.0,0.0 +dairy_cattle,head,0.0,119000.0,961.0 +nitrogen_fertiliser,tonne,0.0,0.0,18100.0 +wastewater_treatment,person,0.0,391.0,68.9 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..a159fd115ddb99113632246ebca122a4282d0d11 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,dairy_cattle,dairy cows kept over the year,211,head +E02,natural_gas_boiler,natural gas burned in boilers,38461,m3 +E03,petrol_combustion,petrol for pool cars,4450.2,litre +E04,wastewater_treatment,people connected to the treatment works,3443,person +E05,heating_oil_boiler,heating oil burned in boilers,32389.1,litre +E06,dairy_cattle,dairy cows kept over the year,506,head diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..35e1f8bb8efae7a05aa313bd82d8bcf84ab327ed --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Ostervik Bakery Group (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..057ab0681716ac07e837a34e618fcbdf30318bad --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 66 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1a7d7fa86a1daa90fdab39ae6894501e1e79fa8d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 25109.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 202.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 756.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 74.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 8.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 1.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 75.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 10.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 3.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 1.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 10.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 1346.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 237.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 100.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 82.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 11.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 0.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 83.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 60214.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 486.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 1814.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 167.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 2427.38, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 246.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 2841.5, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0066/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..a0f47a59b84d8804dd9902593e6135509b8e6be6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.74,0.129,0.142 +petrol_combustion,litre,2.37,0.874,0.266 +heating_oil_boiler,litre,2.42,0.368,0.0178 +natural_gas_boiler,m3,1.98,0.192,0.0365 +wood_chip_boiler,tonne,0.0,351.0,48.5 +landfilled_waste,tonne,0.0,43200.0,0.0 +dairy_cattle,head,0.0,144000.0,1090.0 +nitrogen_fertiliser,tonne,0.0,0.0,18500.0 +wastewater_treatment,person,0.0,477.0,56.6 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..6d2ebb206d58b879c520f3c185e63e27504075d1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/environment/workdir/sources.csv @@ -0,0 +1,7 @@ +source_id,category,description,amount,unit +E01,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),788660,kg +E02,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,64318,kg +E03,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,14.7,tonne +E04,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),216.7,tonne +E05,dairy_cattle,dairy cows kept over the year,315,head +E06,natural_gas_boiler,natural gas burned in boilers,167373,m3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5e9149edb1d020f0a39864d10581104bff6a2b15 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/instruction.md @@ -0,0 +1,20 @@ +# Emissions inventory: three gases + +You are compiling the 2019 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together as tonnes CO2e), each 2 decimals. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee9d32310e3e64e19434302f201c65fd38357a7a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 78 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..3c11b9c2cd56867d017b136a6f0bf4f5d62d5456 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 276.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 38.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 17.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 1189.88, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 315.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 271.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 72.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 76.06, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 10.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 4.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 45360.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 343.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 1361.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 331.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 32.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 6.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 333.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 331.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 1280.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 492.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 2105.17, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d2-t0078/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..551222c180d8126828b8ae51fd65423cb45fe79e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.67,0.0931,0.116 +petrol_combustion,litre,2.22,0.892,0.2 +heating_oil_boiler,litre,2.64,0.416,0.0216 +natural_gas_boiler,m3,1.99,0.181,0.0403 +wood_chip_boiler,tonne,0.0,279.0,48.0 +landfilled_waste,tonne,0.0,61200.0,0.0 +dairy_cattle,head,0.0,107000.0,1120.0 +nitrogen_fertiliser,tonne,0.0,0.0,12600.0 +wastewater_treatment,person,0.0,454.0,52.6 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..f2e9666bd7895bce235d33807caa4bd7ad8fec9d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/refrigerant_log.csv @@ -0,0 +1,5 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,head_office,HFC-32,2.5,1.1 +AC02,head_office,HFC-32,22.2,5.3 +AC03,depot,HFC-32,3.0,0.5 +AC04,warehouse,HFC-32,19.4,5.4 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..4cac75e8bd62c29e365eda2faaf90531e1c936a0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,landfilled_waste,municipal waste sent to landfill,380299,kg +E02,petrol_combustion,petrol for pool cars,19774.4,litre +E03,landfilled_waste,municipal waste sent to landfill,3328173,kg +E04,dairy_cattle,dairy cows kept over the year,126,head +E05,heating_oil_boiler,heating oil burned in boilers,29.782,m3 +E06,landfilled_waste,municipal waste sent to landfill,4549.7,tonne +E07,diesel_combustion,diesel for vehicles and plant,23011.5,litre +E08,landfilled_waste,municipal waste sent to landfill,458642,kg diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc461b381bce418f26c51f85c9dafe0e1a6664df --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2023 greenhouse-gas inventory for Brantholm Municipality (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5b5114fd324a6a794e5f4141eddbd8136833cbeb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "eval"] +isced_f = "0521" +family = "multi-gas" +split = "eval" +seed = 10010 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d0e5770a5d543c94480e9923c8e9da16c5861207 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 23274.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 581.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 43.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 17.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 3.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 45.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 203684.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 5092.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 13482.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 141.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 379.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 78.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 12.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 0.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 79.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 278441.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 6961.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 61.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 2.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 2.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 62.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 28068.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 701.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 8.303, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 98.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E06", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 183.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 13674.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 44.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 13911.07, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0010/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..ecfd31fdca9dcc3caaeb1e7695901f03361705e0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.56,0.0899,0.15 +petrol_combustion,litre,2.22,0.708,0.297 +heating_oil_boiler,litre,2.65,0.283,0.0181 +natural_gas_boiler,m3,2.03,0.175,0.0311 +wood_chip_boiler,tonne,0.0,352.0,37.6 +landfilled_waste,tonne,0.0,48600.0,0.0 +dairy_cattle,head,0.0,136000.0,930.0 +nitrogen_fertiliser,tonne,0.0,0.0,17100.0 +wastewater_treatment,person,0.0,446.0,60.6 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..e16190f8d9b9a6b2fe30a8706945a0537df58c5c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/refrigerant_log.csv @@ -0,0 +1,5 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,head_office,HFC-32,2.0,0.9 +AC02,head_office,HFC-32,10.3,2.1 +AC03,workshop,HFC-32,3.1,0.4 +AC04,workshop,HFC-32,25.6,4.4 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..beb7e098fff4ea02b8cc626a8d2a5860fd1eb9dd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,landfilled_waste,municipal waste sent to landfill,3571.7,tonne +E02,heating_oil_boiler,heating oil burned in boilers,25.24,m3 +E03,wastewater_treatment,people connected to the treatment works,35445,person +E04,landfilled_waste,municipal waste sent to landfill,1368.3,tonne +E05,natural_gas_boiler,natural gas burned in boilers,117492,m3 +E06,natural_gas_boiler,natural gas burned in boilers,53582,m3 +E07,dairy_cattle,dairy cows kept over the year,59,head +E08,landfilled_waste,municipal waste sent to landfill,4424.1,tonne diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..668020ec6f4643a53781b399fdd910e20c62af7d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2020 greenhouse-gas inventory for Kestrel Joinery (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..40037edd89a1eb90c3336a1ce83cf30b76fb815b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "eval"] +isced_f = "0521" +family = "multi-gas" +split = "eval" +seed = 10022 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2020745b36d782fae7899a720453278a9f700a25 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 173584.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 4339.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 66.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 7.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 0.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 67.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 15808.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 2147.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 1035.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 66499.38, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 1662.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 238.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 20.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 3.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 240.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 108.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 9.38, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 1.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 109.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 8024.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 54.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 216.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 215011.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 5375.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 5.265, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 96.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E08", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 414.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 11974.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 658.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 13051.72, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-e0022/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..a30d654d2e97f5995ce4db642e3494b736913bb5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.7,0.123,0.118 +petrol_combustion,litre,2.37,0.849,0.23 +heating_oil_boiler,litre,2.62,0.339,0.0222 +natural_gas_boiler,m3,1.97,0.204,0.0303 +wood_chip_boiler,tonne,0.0,271.0,42.3 +landfilled_waste,tonne,0.0,52600.0,0.0 +dairy_cattle,head,0.0,127000.0,846.0 +nitrogen_fertiliser,tonne,0.0,0.0,15200.0 +wastewater_treatment,person,0.0,422.0,65.9 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..4c358bfab5d5f7ddd567ba4f46b2dde666f89572 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/refrigerant_log.csv @@ -0,0 +1,6 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,depot,HFC-134a,37.5,5.0 +AC02,warehouse,HFC-134a,22.6,5.8 +AC03,workshop,HFC-134a,4.3,0.8 +AC04,head_office,HFC-32,1.2,0.4 +AC05,workshop,HFC-32,10.1,3.8 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..6d33fb81e5520d82909fa8a357374f61143391ae --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,landfilled_waste,municipal waste sent to landfill,634.4,tonne +E02,wastewater_treatment,people connected to the treatment works,2286,person +E03,petrol_combustion,petrol for pool cars,6971.6,litre +E04,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),311889,kg +E05,heating_oil_boiler,heating oil burned in boilers,12204,litre +E06,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,18880,kg +E07,natural_gas_boiler,natural gas burned in boilers,89616,m3 +E08,dairy_cattle,dairy cows kept over the year,256,head diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6615e4b6f7b43f6dd32ffbd905fb9eb12d8d1c1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2021 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8df83a5a70660406f39654b8a1bf4ebb2d7af9f0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 10 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..7138b40f2c4f519b2a6df9ae1226c8d587b94475 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 33369.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 834.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 964.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 150.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 69.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 16.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 5.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 1.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 17.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 84.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 13.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 6.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 31.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 4.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 0.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 32.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 286.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 85.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 176.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 18.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 2.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 177.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 32512.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 216.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 877.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 19.423, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 89.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E08", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 225.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 1673.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 200.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 2118.69, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0010/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..a01bd2ee76c1018b02ca57bd627754437a29a07d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.78,0.122,0.153 +petrol_combustion,litre,2.29,0.797,0.286 +heating_oil_boiler,litre,2.55,0.391,0.02 +natural_gas_boiler,m3,2.08,0.223,0.0404 +wood_chip_boiler,tonne,0.0,360.0,48.2 +landfilled_waste,tonne,0.0,43000.0,0.0 +dairy_cattle,head,0.0,124000.0,849.0 +nitrogen_fertiliser,tonne,0.0,0.0,15700.0 +wastewater_treatment,person,0.0,370.0,72.7 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..a30e9f47ec8fd8791f1cdb200627db3d6ef7f52d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/refrigerant_log.csv @@ -0,0 +1,5 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,warehouse,HFC-134a,19.9,4.2 +AC02,warehouse,HFC-32,31.0,5.4 +AC03,workshop,HFC-134a,18.7,5.2 +AC04,warehouse,HFC-134a,27.5,5.9 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..fd8829aa6a34be7330fecba1db6bb191b21d10f0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,wastewater_treatment,people connected to the treatment works,15898,person +E02,landfilled_waste,municipal waste sent to landfill,2148687,kg +E03,wastewater_treatment,people connected to the treatment works,18240,person +E04,petrol_combustion,petrol for pool cars,10643.5,litre +E05,wastewater_treatment,people connected to the treatment works,19119,person +E06,wastewater_treatment,people connected to the treatment works,30757,person +E07,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),75998,kg +E08,heating_oil_boiler,heating oil burned in boilers,10.679,m3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85785061ac158581037377f472a467e2dca70c05 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2020 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..54239fc6113f1723da7ea37830082141bd0b6ab3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 22 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a9047473ead0b16d1e879ff08a3db6946ea75d93 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 5882.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 1155.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 470.99, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 92393.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 2587.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 6748.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 1326.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 540.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 24.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 8.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 3.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 25.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 7074.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 1389.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 566.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 11380.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 2236.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 911.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 27.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 3.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 1.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 27.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 4.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 0.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 27.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 23.546, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 99.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E02", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 51.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 3458.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 1620.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 5154.08, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0022/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..7ac9cb6762a93c8383e88c0bba76dda4c8ee66d6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.74,0.128,0.12 +petrol_combustion,litre,2.32,0.938,0.202 +heating_oil_boiler,litre,2.52,0.401,0.0197 +natural_gas_boiler,m3,2.09,0.219,0.0295 +wood_chip_boiler,tonne,0.0,287.0,41.8 +landfilled_waste,tonne,0.0,55100.0,0.0 +dairy_cattle,head,0.0,116000.0,790.0 +nitrogen_fertiliser,tonne,0.0,0.0,17200.0 +wastewater_treatment,person,0.0,414.0,73.7 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..9a271314cf0f66b3d1e569fc6c637095d848bb75 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/refrigerant_log.csv @@ -0,0 +1,5 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,depot,HFC-134a,6.7,1.4 +AC02,workshop,HFC-32,8.9,2.7 +AC03,head_office,HFC-32,18.2,2.6 +AC04,warehouse,HFC-32,2.4,0.7 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..218145bd1b65f085fa08d2c3da12715a013501c6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,heating_oil_boiler,heating oil burned in boilers,13.16,m3 +E02,landfilled_waste,municipal waste sent to landfill,3400750,kg +E03,wastewater_treatment,people connected to the treatment works,2106,person +E04,petrol_combustion,petrol for pool cars,17069.4,litre +E05,natural_gas_boiler,natural gas burned in boilers,77236,m3 +E06,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,21309,kg +E07,landfilled_waste,municipal waste sent to landfill,4742982,kg +E08,dairy_cattle,dairy cows kept over the year,554,head diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d1bcfec7afe2e3e09526429108d7a8463418cffb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Harlow Fold Logistics (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d11ddd49d49f9def0b66a68b00842ab99ef909d1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 34 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..03b2fbc08230ab833883a13326b872fe70a5f801 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 33.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 5.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 33.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 187381.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 4684.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 871.88, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 155.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 68.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 39.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 16.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 3.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 41.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 161.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 16.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 2.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 162.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 366.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 109.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 261338.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 6533.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 64264.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 437.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 1737.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 6.052, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 98.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E07", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 234.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 12847.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 287.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 13375.26, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0034/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..aa3f42389bdf3263eaccdc91c230acc47e507921 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.78,0.127,0.16 +petrol_combustion,litre,2.3,0.739,0.25 +heating_oil_boiler,litre,2.44,0.404,0.0235 +natural_gas_boiler,m3,1.99,0.214,0.0311 +wood_chip_boiler,tonne,0.0,337.0,44.0 +landfilled_waste,tonne,0.0,60900.0,0.0 +dairy_cattle,head,0.0,122000.0,1030.0 +nitrogen_fertiliser,tonne,0.0,0.0,15200.0 +wastewater_treatment,person,0.0,439.0,57.4 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..f8dfe9fb13f3baa43e03e68c50f71b07b46a6486 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/refrigerant_log.csv @@ -0,0 +1,5 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,workshop,HFC-32,8.1,2.8 +AC02,head_office,HFC-134a,18.8,3.9 +AC03,warehouse,HFC-134a,14.6,5.6 +AC04,warehouse,HFC-134a,18.1,5.3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..73b822813480f334a38a693130cde10a368870a0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,natural_gas_boiler,natural gas burned in boilers,146178,m3 +E02,petrol_combustion,petrol for pool cars,4379.6,litre +E03,heating_oil_boiler,heating oil burned in boilers,34128.6,litre +E04,diesel_combustion,diesel for vehicles and plant,25711.2,litre +E05,dairy_cattle,dairy cows kept over the year,544,head +E06,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),479.6,tonne +E07,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),402488,kg +E08,wastewater_treatment,people connected to the treatment works,13578,person diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e101f985b9c7db30080b632c948b3623d6035681 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2019 greenhouse-gas inventory for Lindqvist Castings (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c8f72c4bb03deef959cc208921b55b64cd0c9602 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 46 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..91666341bccc34b00d8c734fc45d8f9e543fd4b8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 290.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 31.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 4.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 293.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 10.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 3.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 1.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 10.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 83.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 13.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 0.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 83.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 71.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 3.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 4.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 72.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 66368.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 560.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 1826.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 161.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 21.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 10.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 135.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 17.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 8.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 5960.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 779.38, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 381.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 23.054, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 83.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E05", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 455.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 1816.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 413.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 2709.65, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0046/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..bc354cf66e94398dcde9046606faa7ff28e9fb29 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.8,0.0958,0.158 +petrol_combustion,litre,2.36,0.826,0.268 +heating_oil_boiler,litre,2.5,0.319,0.0205 +natural_gas_boiler,m3,2.05,0.177,0.0338 +wood_chip_boiler,tonne,0.0,261.0,33.6 +landfilled_waste,tonne,0.0,53000.0,0.0 +dairy_cattle,head,0.0,114000.0,774.0 +nitrogen_fertiliser,tonne,0.0,0.0,17500.0 +wastewater_treatment,person,0.0,410.0,58.7 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..0055cfc033b1e8c0ba167aafe9c2c04965cdb33d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fourth Assessment Report (2007). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 25 | +| N2O | 298 | +| HFC-134a | 1430 | +| HFC-32 | 675 | +| SF6 | 22800 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..faa6b139c209fb884647681eae9853d1636e99c4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/refrigerant_log.csv @@ -0,0 +1,4 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,depot,HFC-134a,23.1,3.3 +AC02,head_office,HFC-32,24.6,4.7 +AC03,depot,HFC-32,3.5,0.6 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..7b9582f42b0bc7a90d8a473f7fea1686c9edf1e0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,heating_oil_boiler,heating oil burned in boilers,5256.5,litre +E02,landfilled_waste,municipal waste sent to landfill,2678886,kg +E03,dairy_cattle,dairy cows kept over the year,349,head +E04,landfilled_waste,municipal waste sent to landfill,3499219,kg +E05,wastewater_treatment,people connected to the treatment works,39723,person +E06,wastewater_treatment,people connected to the treatment works,16095,person +E07,diesel_combustion,diesel for vehicles and plant,15268.8,litre +E08,nitrogen_fertiliser,nitrogen applied as mineral fertiliser,26.4,tonne diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96de05862ef475cb9181ba42105149b7b188f901 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Brantholm Municipality (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c848618f0c69c2be048a0ee9ddd9e2cd04cc91a2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 58 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..888a9a1c753355a841f0a4c7444e10c9e6434db3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 13.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 1.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 0.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 13.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 141980.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 3549.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 39786.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 270.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 1075.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 185458.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 4636.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 16286.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 2331.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 1102.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 6598.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 944.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 446.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 42.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 1.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 2.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 43.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 462.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 137.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 8.296, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 99.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E04", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 55.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 9752.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 1195.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 11012.37, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0058/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..61ac0c5d0b7c2d30480584c65e39d9d39ad3f879 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.67,0.0903,0.118 +petrol_combustion,litre,2.38,0.922,0.234 +heating_oil_boiler,litre,2.44,0.364,0.0217 +natural_gas_boiler,m3,2.0,0.216,0.0356 +wood_chip_boiler,tonne,0.0,306.0,42.8 +landfilled_waste,tonne,0.0,62000.0,0.0 +dairy_cattle,head,0.0,130000.0,961.0 +nitrogen_fertiliser,tonne,0.0,0.0,15200.0 +wastewater_treatment,person,0.0,466.0,57.2 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..cdecab5aa7ad720032c63e1eefe211ce5ff7dd06 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/refrigerant_log.csv @@ -0,0 +1,4 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,depot,HFC-134a,32.4,4.6 +AC02,workshop,HFC-32,8.6,2.4 +AC03,depot,HFC-32,4.1,1.3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..e6ae4cffb30682d74ae9c9fdc67c29b5024abbea --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,wastewater_treatment,people connected to the treatment works,21890,person +E02,diesel_combustion,diesel for vehicles and plant,51704.6,litre +E03,natural_gas_boiler,natural gas burned in boilers,32567,m3 +E04,wastewater_treatment,people connected to the treatment works,34233,person +E05,heating_oil_boiler,heating oil burned in boilers,7213.8,litre +E06,heating_oil_boiler,heating oil burned in boilers,34.98,m3 +E07,wastewater_treatment,people connected to the treatment works,13900,person +E08,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),759.5,tonne diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a7beb904af7d295243ef45986361134f07b50c3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2024 greenhouse-gas inventory for Tarnwick Borough Council (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9a97d40f7e627361d5d9fb9bfb02a8e072df03f0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 70 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..37978b6de54c716631285e139e77169d0bcbb85a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 10200.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 1252.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 617.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 138.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 4.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 6.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 139.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 65.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 7.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 1.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 65.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 15952.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 1958.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 965.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 17.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 2.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 0.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 17.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 85.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 12.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 0.76, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 85.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 6477.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 795.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 392.06, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 232.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 32.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 15.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 8.485, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 86.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E04", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 306.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 920.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 1072.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 2307.74, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0070/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/gas_factors.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/gas_factors.csv new file mode 100644 index 0000000000000000000000000000000000000000..d46e1aeaa1a9270d4ff38097ce9e44ddcf2a8410 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/gas_factors.csv @@ -0,0 +1,10 @@ +category,unit,co2_kg_per_unit,ch4_g_per_unit,n2o_g_per_unit +diesel_combustion,litre,2.6,0.112,0.126 +petrol_combustion,litre,2.32,0.745,0.267 +heating_oil_boiler,litre,2.54,0.306,0.0234 +natural_gas_boiler,m3,1.94,0.187,0.0355 +wood_chip_boiler,tonne,0.0,292.0,47.0 +landfilled_waste,tonne,0.0,49300.0,0.0 +dairy_cattle,head,0.0,142000.0,815.0 +nitrogen_fertiliser,tonne,0.0,0.0,15100.0 +wastewater_treatment,person,0.0,348.0,65.6 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/gwp_values.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/gwp_values.md new file mode 100644 index 0000000000000000000000000000000000000000..01d881e0a560d1e0d87cfc15ad9d9cfa50ec2de3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/gwp_values.md @@ -0,0 +1,14 @@ +# Global warming potentials + +100-year values from the IPCC Fifth Assessment Report (2013). Use these values, not any others you may know. + +| gas | GWP | +|---|---| +| CO2 | 1 | +| CH4 | 28 | +| N2O | 265 | +| HFC-134a | 1300 | +| HFC-32 | 677 | +| SF6 | 23500 | + +CO2e of a gas = mass of the gas x its GWP. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/refrigerant_log.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/refrigerant_log.csv new file mode 100644 index 0000000000000000000000000000000000000000..b7db29344ea8ab88db4d2d23b6223714fd484661 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/refrigerant_log.csv @@ -0,0 +1,4 @@ +unit_id,location,refrigerant,charge_kg,topped_up_kg +AC01,head_office,HFC-32,9.8,3.0 +AC02,workshop,HFC-134a,28.0,3.7 +AC03,depot,HFC-32,20.9,4.4 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/sources.csv b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/sources.csv new file mode 100644 index 0000000000000000000000000000000000000000..9c76fef7888d50806365e9805b9bd8c16e9f50df --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/environment/workdir/sources.csv @@ -0,0 +1,9 @@ +source_id,category,description,amount,unit +E01,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),310.2,tonne +E02,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),588291,kg +E03,landfilled_waste,municipal waste sent to landfill,786972,kg +E04,diesel_combustion,diesel for vehicles and plant,39.153,m3 +E05,wood_chip_boiler,wood chips burned (biogenic CO2 not counted),284380,kg +E06,landfilled_waste,municipal waste sent to landfill,4419676,kg +E07,dairy_cattle,dairy cows kept over the year,513,head +E08,diesel_combustion,diesel for vehicles and plant,45.776,m3 diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/instruction.md b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1ff59470923c4d03ef19fd1e4e2b46f4b84f52b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/instruction.md @@ -0,0 +1,23 @@ +# Emissions inventory: three gases + +You are compiling the 2019 greenhouse-gas inventory for Harlow Fold Logistics (a synthetic organisation), gas by gas. + +- `sources.csv`: the emission sources and their activity amounts. +- `gas_factors.csv`: for each category, the emissions per unit of activity: CO2 in kg, CH4 in grams and N2O in grams. +- `gwp_values.md`: the global warming potentials to use. + +Some amounts are in a different unit from their category's factors: convert first, using 1 m3 = 1000 litres and 1 tonne = 1000 kg. `refrigerant_log.csv` lists the cooling units serviced in the year: take the refrigerant topped up (`topped_up_kg`) as the amount that leaked, and convert it to CO2e with the GWP of that refrigerant. The charge is for information only. + +Write `answer.json` in this folder, a JSON object with: + +- `sources`: an object keyed by `source_id`, each with + - `co2_t`: CO2 emitted, in tonnes, 2 decimals. + - `ch4_kg`: CH4 emitted, in kg, 2 decimals. + - `n2o_kg`: N2O emitted, in kg, 2 decimals. + - `co2e_t`: the three gases together in tonnes CO2e, 2 decimals. +- `totals`: an object with `co2_t` (all CO2, tonnes), `ch4_t_co2e` (all CH4 as tonnes CO2e), `n2o_t_co2e` (all N2O as tonnes CO2e) and `co2e_t` (everything together, including the refrigerant leaks, as tonnes CO2e), each 2 decimals. +- `refrigerants_t_co2e`: the refrigerant leaks in tonnes CO2e, 3 decimals. +- `non_co2_share_percent`: the share of `totals.co2e_t` that does not come from CO2 (CH4, N2O and refrigerants), in percent, 1 decimal. +- `largest_source`: the `source_id` in `sources.csv` with the largest CO2e. + +1 tonne = 1000 kg = 1 000 000 g. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/task.toml b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f1de49ff6448300935e35f2036d0804103642818 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "multi-gas", "isced-0521", "train"] +isced_f = "0521" +family = "multi-gas" +split = "train" +seed = 82 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d8c80dae10783a417d74b50ac03594ea86bde80f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/checks.json @@ -0,0 +1,274 @@ +[ + { + "path": "sources.E01.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.ch4_kg", + "type": "number", + "value": 90.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.n2o_kg", + "type": "number", + "value": 14.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E01.co2e_t", + "type": "number", + "value": 6.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.ch4_kg", + "type": "number", + "value": 171.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.n2o_kg", + "type": "number", + "value": 27.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E02.co2e_t", + "type": "number", + "value": 12.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.ch4_kg", + "type": "number", + "value": 38797.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E03.co2e_t", + "type": "number", + "value": 1086.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2_t", + "type": "number", + "value": 101.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.ch4_kg", + "type": "number", + "value": 4.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.n2o_kg", + "type": "number", + "value": 4.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E04.co2e_t", + "type": "number", + "value": 103.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.ch4_kg", + "type": "number", + "value": 83.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.n2o_kg", + "type": "number", + "value": 13.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E05.co2e_t", + "type": "number", + "value": 5.87, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.ch4_kg", + "type": "number", + "value": 217890.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.n2o_kg", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E06.co2e_t", + "type": "number", + "value": 6100.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2_t", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.ch4_kg", + "type": "number", + "value": 72846.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.n2o_kg", + "type": "number", + "value": 418.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E07.co2e_t", + "type": "number", + "value": 2150.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2_t", + "type": "number", + "value": 119.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.ch4_kg", + "type": "number", + "value": 5.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.n2o_kg", + "type": "number", + "value": 5.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "sources.E08.co2e_t", + "type": "number", + "value": 120.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "refrigerants_t_co2e", + "type": "number", + "value": 9.82, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "non_co2_share_percent", + "type": "number", + "value": 97.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "largest_source", + "type": "str", + "value": "E06", + "weight": 2 + }, + { + "path": "totals.co2_t", + "type": "number", + "value": 220.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.ch4_t_co2e", + "type": "number", + "value": 9236.88, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.n2o_t_co2e", + "type": "number", + "value": 128.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "totals.co2e_t", + "type": "number", + "value": 9595.88, + "abs_tol": 0.01, + "weight": 2 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-multi-gas-d3-t0082/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..cb163eb670224268d7e7192679667703400696c9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2020,580.4,3656.1,6526.6,30622 +2018,615.2,3653.6,7641.8,29028 +2019,551.5,3819.3,6940.8,29424 +2021,566.7,3621.2,6780.6,30962 +2017,601.9,4003.1,7975.7,28807 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..de98148c430d683c1bf02cae444742c44484b3ea --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Ostervik Bakery Group + +- Base year: 2017 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 40 % below the base-year total. +- Output measure: tonnes of product. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..30de9eff0f8169bc64da95608e0aea2b04b9a4a3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (tonnes of product). The rows are in no particular order. `target.md` gives the base year and the reduction target of Ostervik Bakery Group (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2017"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2017. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2017. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2021 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..59fa0b92c6601f348963beaaaedd0d880cc22054 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "eval"] +isced_f = "0521" +family = "time-series" +split = "eval" +seed = 10003 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..32011834a2b81d2af2ce81b309e311a17689159b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 12580.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 436.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 11910.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 410.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 11311.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 384.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -5.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -10.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 10763.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 351.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -4.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -14.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 10968.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 354.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": 1.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -12.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 7548.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 488.6, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0003/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..1d01f0b0501b4dee2bd3199a8470acb18110a0bf --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2022,1524.5,6191.2,5955.9,27191 +2019,1441.3,7340.9,6262.9,24956 +2018,1457.2,6999.1,5982.6,24536 +2021,1514.8,6707.9,6419.2,25499 +2020,1493.1,6730.7,6632.0,25360 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..b738ea87cb581c0d71d7ac01181d19f730b131b3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Ostervik Bakery Group + +- Base year: 2018 +- Target year: 2029 +- Target: total emissions (scopes 1 to 3) 45 % below the base-year total. +- Output measure: tonnes of product. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa20c5e9663d8216160008b67fbc3d7c9865fc34 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (tonnes of product). The rows are in no particular order. `target.md` gives the base year and the reduction target of Ostervik Bakery Group (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2018"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2018. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2018. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2022 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..97df38d67d9ce6887305da402e0a8e3af54c0a0c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "eval"] +isced_f = "0521" +family = "time-series" +split = "eval" +seed = 10015 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f7e6f0cbefa84a96d3866fa9ebb210a3d8704cf0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 14438.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 588.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 15045.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 602.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": 4.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": 4.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 14855.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 585.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -1.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": 2.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 14641.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 574.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -1.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": 1.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 13671.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 502.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -6.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 7941.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 818.6, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-e0015/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..3600261953c537f6abc41afd19ae87ab9c2c4825 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2021,551.6,6658.7,648.6,67262 +2017,629.4,8548.8,707.5,57744 +2018,621.5,8372.6,732.4,58651 +2019,590.4,7750.6,700.8,60026 +2020,614.1,6899.6,629.0,63501 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..f78176fbf01febc0608616dfa63ac11a0de1c3d0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Marrow Vale Housing + +- Base year: 2017 +- Target year: 2027 +- Target: total emissions (scopes 1 to 3) 30 % below the base-year total. +- Output measure: tonnes of product. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c29450aaea501f0880b73a598089713b3ef18b67 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (tonnes of product). The rows are in no particular order. `target.md` gives the base year and the reduction target of Marrow Vale Housing (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2017"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2017. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2017. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2021 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b4fe8f7010b73c631cfe7eb359b8b5c25975de07 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 3 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..df706d2265aaaa570497246aa71a492b19601708 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 9885.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 171.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 9726.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 165.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 9041.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 150.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -7.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -8.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 8142.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 128.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -9.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -17.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 7858.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 116.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -3.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -20.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 6920.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 156.5, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0003/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..db7923b664c5e51e22a887a9830d2d03f865c54b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2021,7010.0,2107.1,2006.6,9589 +2018,6959.5,1966.3,2257.9,9011 +2019,7016.4,1955.1,2166.1,9414 +2020,7424.2,2065.9,2107.6,9770 +2017,7758.0,2180.7,2281.9,9026 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..536f99241a7bf177c283b4ac097ae44455863b12 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Lindqvist Castings + +- Base year: 2017 +- Target year: 2026 +- Target: total emissions (scopes 1 to 3) 45 % below the base-year total. +- Output measure: thousand parcels delivered. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71110fab24f448960d4bb60587707bcd3e4f9e7f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (thousand parcels delivered). The rows are in no particular order. `target.md` gives the base year and the reduction target of Lindqvist Castings (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2017"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2017. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2017. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2021 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ddc9de960ade6fd70d2fbb1124807ea925f4f83 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 15 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..3900be1cdce192fbcecb9e31f2b1f22618198107 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 12220.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 1353.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 11183.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 1241.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -8.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -8.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 11137.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 1183.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -0.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -8.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 11597.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 1187.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": 4.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -5.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 11123.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 1160.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -4.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -9.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 6721.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 880.5, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0015/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..015ac90b3e5409950f9f9c2e1cb5f453be640a40 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2016,6336.5,2049.1,4842.1,159500 +2020,5224.9,1717.2,3600.7,151800 +2017,5870.0,1983.5,4458.8,153913 +2018,5363.9,1818.0,4390.8,164002 +2019,4985.7,1876.1,3983.5,156202 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..f7eed7649d6b5df97f5d1f05f50ee04d6e446271 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Marrow Vale Housing + +- Base year: 2016 +- Target year: 2027 +- Target: total emissions (scopes 1 to 3) 42 % below the base-year total. +- Output measure: m2 of heated floor area. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f010efb299e0e3c4c59ac5dc88470a97e27f699a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (m2 of heated floor area). The rows are in no particular order. `target.md` gives the base year and the reduction target of Marrow Vale Housing (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2020 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee59e56eaee001a8cc08001abce123e02f24dcf8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 27 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2bd74fb81a839328ac598652c9159fd84702ecae --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 13227.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 82.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 12312.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 80.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -6.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -6.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 11572.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 70.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -6.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -12.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 10845.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 69.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -6.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -18.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 10542.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 69.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -2.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -20.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 7672.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 410.1, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0027/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..541b48308dc114d547abfe8bbcfaa3b8c6544c8f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2018,1670.6,1123.6,3231.2,11362 +2019,1763.5,1016.3,3138.9,11703 +2016,1631.7,1227.3,3094.3,10721 +2020,1582.6,1036.7,3195.4,12030 +2017,1668.8,1125.8,3093.1,11358 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..9aff87176939575f4a5eb8d6f2e567b47b42c36a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Brantholm Municipality + +- Base year: 2016 +- Target year: 2027 +- Target: total emissions (scopes 1 to 3) 50 % below the base-year total. +- Output measure: tonnes of product. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49a1fbe4c3ba4ac423e65861fefecbe0f5139791 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (tonnes of product). The rows are in no particular order. `target.md` gives the base year and the reduction target of Brantholm Municipality (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2020 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..114db04d99d3d5f5204cc7f544beeb254dfcb1bf --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 39 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..db622d23152d79788e2c60b942ea85839d652682 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 5953.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 555.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 5887.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 518.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -1.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -1.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 6025.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 530.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": 2.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": 1.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 5918.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 505.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -0.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 5814.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 483.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -1.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -2.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 2976.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 405.4, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0039/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..11b261d8e89aa691c0ad2b6fa36f2f24f255cd7b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2017,5800.2,1127.3,3628.3,54640 +2020,5379.9,1034.5,3434.0,49663 +2016,6417.5,1183.7,3437.2,51501 +2018,5745.5,1067.6,3448.2,52962 +2019,5131.4,1087.9,3398.3,51464 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..e8bf859fcdfea3eaa978206bf4641bb702e919d5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Marrow Vale Housing + +- Base year: 2016 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 45 % below the base-year total. +- Output measure: residents. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de128f38daf453238fe1a058187578f5d4d31441 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (residents). The rows are in no particular order. `target.md` gives the base year and the reduction target of Marrow Vale Housing (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2020 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..78776e0b3df6ab6bb13cc362e4de60bfee07badf --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 51 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a53db89404c07e36b326972d1311d7c3958b85e9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 11038.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 214.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 10555.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 193.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -4.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -4.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 10261.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 193.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -2.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -7.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 9617.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 186.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -6.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -12.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 9848.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 198.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": 2.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -10.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 6071.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 472.2, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0051/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..deac26fa7b2d3d50e118ab8cd48acfe9c23eb6ce --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2018,3644.8,3289.9,4949.0,194317 +2017,3659.6,3225.5,4924.3,187277 +2019,3355.4,3152.7,5125.4,196426 +2020,3052.3,2924.5,5038.9,204348 +2016,3657.4,3225.0,4675.9,182850 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..1126d88efd8e7239b0c794fa0abbc70bf55f263d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Marrow Vale Housing + +- Base year: 2016 +- Target year: 2029 +- Target: total emissions (scopes 1 to 3) 30 % below the base-year total. +- Output measure: m2 of heated floor area. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f010efb299e0e3c4c59ac5dc88470a97e27f699a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (m2 of heated floor area). The rows are in no particular order. `target.md` gives the base year and the reduction target of Marrow Vale Housing (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2020 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9807535f3593352288734b6242b5966c33431913 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 63 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..47e349b416fe7d06aa8fcff5121e5aff490154b1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 11558.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 63.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 11809.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 63.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": 2.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": 2.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 11883.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 61.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": 0.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": 2.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 11633.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 59.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -2.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": 0.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 11015.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 53.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -4.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 8090.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 325.0, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0063/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/workdir/annual_emissions.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/workdir/annual_emissions.csv new file mode 100644 index 0000000000000000000000000000000000000000..568433873ef1c58cffa432005fe060b2180a090b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/workdir/annual_emissions.csv @@ -0,0 +1,6 @@ +year,scope_1_t,scope_2_t,scope_3_t,output +2016,5509.3,4789.5,5930.2,114247 +2019,4848.7,4808.8,5897.1,123264 +2020,4756.3,4493.0,5770.6,129555 +2018,5304.1,4869.8,5894.0,116073 +2017,5802.3,4653.1,5863.5,111105 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..5f69124ccbac2ac0f7c05bcbba7c0249c54f3324 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Ostervik Bakery Group + +- Base year: 2016 +- Target year: 2026 +- Target: total emissions (scopes 1 to 3) 40 % below the base-year total. +- Output measure: residents. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f096c5a4e24a6c9238c86bf826568ee80b73b286 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/instruction.md @@ -0,0 +1,15 @@ +# Emissions inventory: trend and target + +`annual_emissions.csv` gives the emissions of each year by scope in tonnes CO2e and the year's output (residents). The rows are in no particular order. `target.md` gives the base year and the reduction target of Ostervik Bakery Group (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2020 total to the target by the target year: (latest total - target) / years left, 1 decimal. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..694224086e04d0c2a5de44e02ba21e31f361786a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 75 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..eacaf728067ff3e57fd0889b4df49d53345bd650 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/checks.json @@ -0,0 +1,142 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 16229.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 142.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 16318.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 146.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": 0.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": 0.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 16067.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 138.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -1.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -1.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 15554.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 126.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -3.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -4.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 15019.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 115.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -3.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -7.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 9737.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 880.4, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d1-t0075/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..c03b10845f5b4dfa9e3ac428cc6fa4292bdf0c8d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/emissions_ledger.csv @@ -0,0 +1,55 @@ +year,site,scope,amount,unit +2019,Cedar,3,244.6,t +2023,Cedar,2,2363.1,t +2018,Alder,1,237900,kg +2018,Birch,1,331.5,t +2019,Birch,1,309.8,t +2020,Cedar,3,257.2,t +2019,Birch,3,1354.4,t +2020,Birch,1,325.1,t +2023,Cedar,1,2668.7,t +2021,Cedar,2,2494.6,t +2019,Alder,3,2855.3,t +2019,Cedar,1,2856300,kg +2022,Birch,2,1083.4,t +2019,Alder,2,2091.6,t +2021,Birch,1,334.2,t +2021,Birch,2,1121000,kg +2020,Alder,3,2767.3,t +2020,Cedar,1,2710.4,t +2019,Cedar,2,2441.4,t +2021,Alder,1,208700,kg +2018,Birch,3,1332.5,t +2022,Cedar,1,2629.8,t +2020,Birch,3,1343.9,t +2021,Alder,2,2161.5,t +2018,Alder,3,2773800,kg +2021,Alder,3,2830600,kg +2018,Cedar,1,2750.5,t +2021,Birch,3,1320.1,t +2019,Birch,2,1037100,kg +2023,Birch,1,314000,kg +2018,Alder,2,2078.7,t +2022,Birch,3,1204.1,t +2021,Cedar,1,2515.8,t +2023,Alder,1,182500,kg +2022,Cedar,2,2244.8,t +2020,Alder,1,220.4,t +2021,Cedar,3,250400,kg +2019,Alder,1,211.7,t +2022,Alder,3,2599.2,t +2023,Birch,3,1236.5,t +2018,Cedar,2,2650.9,t +2022,Birch,1,342.0,t +2020,Birch,2,1093200,kg +2020,Cedar,2,2533.8,t +2020,Alder,2,2193.5,t +2023,Alder,2,1813.6,t +2023,Alder,3,2623.2,t +2018,Birch,2,1139.1,t +2023,Birch,2,1024.8,t +2022,Alder,2,2024.9,t +2022,Cedar,3,229800,kg +2023,Cedar,3,237100,kg +2022,Alder,1,194.8,t +2018,Cedar,3,270.7,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..86afa37bdc0bc28a09c85ad2cdb15ab760569f50 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2022,125079 +2023,122861 +2020,119437 +2019,114204 +2018,115667 +2021,122431 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..6215ff51a8db87dd468c1deb6374cfd360eb6ec5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Ostervik Bakery Group + +- Base year: 2018 +- Target year: 2027 +- Target: total emissions (scopes 1 to 3) 25 % below the base-year total. +- Output measure: m2 of heated floor area. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ef49ab40f52b6abd5ca2e0d218ace2d06e0fd24 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (m2 of heated floor area). `target.md` gives the base year and the reduction target of Ostervik Bakery Group (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2018"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2018. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2018. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2023 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2023, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2023 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a1d6a5ed5b556bf0a50b826e46f656c05e2744ec --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "eval"] +isced_f = "0521" +family = "time-series" +split = "eval" +seed = 10007 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8a9fb0dd14ba02d4c768f0254732930b202e3457 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 13565.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 117.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 13402.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 117.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -1.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 13444.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 112.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": 0.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -0.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 13236.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 108.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -1.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -2.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 12552.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 100.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -5.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -7.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.total_t_co2e", + "type": "number", + "value": 12463.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.intensity_kg_per_unit", + "type": "number", + "value": 101.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_previous_percent", + "type": "number", + "value": -0.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_base_percent", + "type": "number", + "value": -8.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 10174.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 572.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 11681.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0007/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..0400325e07eb10b6548994993e51cde5d681263a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/emissions_ledger.csv @@ -0,0 +1,55 @@ +year,site,scope,amount,unit +2015,Cedar,1,2228.1,t +2016,Dunlin,3,582500,kg +2020,Dunlin,2,106.7,t +2019,Cedar,3,182.4,t +2015,Dunlin,2,103100,kg +2019,Alder,1,561.0,t +2016,Dunlin,1,853.9,t +2018,Alder,3,1988.3,t +2019,Dunlin,2,102.7,t +2017,Dunlin,3,524.1,t +2016,Alder,3,1871.6,t +2018,Cedar,2,856.8,t +2015,Alder,3,1905.8,t +2017,Alder,1,594.7,t +2016,Cedar,2,789500,kg +2018,Cedar,3,178800,kg +2020,Cedar,3,191.6,t +2016,Alder,1,639.5,t +2017,Alder,2,2614.9,t +2019,Alder,3,1977.0,t +2019,Cedar,2,843.9,t +2020,Alder,2,2252000,kg +2019,Cedar,1,1941.2,t +2016,Cedar,1,2180400,kg +2015,Cedar,2,771.8,t +2015,Alder,1,606.9,t +2017,Cedar,1,1994500,kg +2019,Dunlin,3,511000,kg +2020,Alder,3,1836.1,t +2016,Cedar,3,168800,kg +2015,Cedar,3,165600,kg +2019,Alder,2,2448.0,t +2018,Dunlin,2,103.7,t +2017,Dunlin,2,101.8,t +2020,Dunlin,3,492400,kg +2017,Dunlin,1,771700,kg +2017,Alder,3,1924300,kg +2017,Cedar,3,177.5,t +2020,Cedar,1,1728.8,t +2018,Cedar,1,1938.3,t +2020,Alder,1,591.4,t +2017,Cedar,2,834200,kg +2015,Dunlin,3,621.5,t +2016,Dunlin,2,109.0,t +2016,Alder,2,2884000,kg +2018,Alder,1,564.3,t +2018,Dunlin,3,553.7,t +2015,Dunlin,1,886.8,t +2019,Dunlin,1,691.1,t +2020,Cedar,2,842.9,t +2015,Alder,2,2844000,kg +2018,Dunlin,1,737800,kg +2020,Dunlin,1,635.0,t +2018,Alder,2,2719000,kg diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..c64851a71a0d1a8eb57e8efa04311f9696afd9eb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2016,85723 +2020,88483 +2015,81198 +2019,84861 +2017,87362 +2018,86892 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..6d368d9ab1594b06d921944f00ef22b2f4f5cd09 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Marrow Vale Housing + +- Base year: 2015 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 30 % below the base-year total. +- Output measure: residents. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3147adcf04d122a6faebca7a4fb3994fe0a52a7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (residents). `target.md` gives the base year and the reduction target of Marrow Vale Housing (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2015"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2015. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2015. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2020 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2020, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2020 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf34ff67f4f8f21373c232f577b01cc61ca4187f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "eval"] +isced_f = "0521" +family = "time-series" +split = "eval" +seed = 10019 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..24700a52f2b21fdde4b7467453f4857aa9f8e22f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2015.total_t_co2e", + "type": "number", + "value": 10133.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2015.intensity_kg_per_unit", + "type": "number", + "value": 124.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 10079.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 117.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.change_vs_previous_percent", + "type": "number", + "value": -0.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.change_vs_base_percent", + "type": "number", + "value": -0.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 9537.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 109.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -5.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -5.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 9640.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 111.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": 1.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -4.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 9258.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 109.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -4.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -8.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 8676.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 98.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -6.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -14.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 7093.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 197.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 8964.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": true, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-e0019/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..8786383a2a3a3ea8c2d490973a84d653596f0985 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/emissions_ledger.csv @@ -0,0 +1,73 @@ +year,site,scope,amount,unit +2017,Alder,3,123.6,t +2022,Cedar,2,1014700,kg +2021,Cedar,2,997.5,t +2018,Alder,1,1565.9,t +2018,Cedar,1,471.9,t +2022,Cedar,3,492.9,t +2019,Dunlin,2,1407100,kg +2020,Alder,3,117000,kg +2017,Elm,1,364.8,t +2017,Alder,1,1670.0,t +2018,Cedar,2,1026.5,t +2021,Cedar,3,471.9,t +2020,Cedar,1,409300,kg +2022,Elm,3,260700,kg +2022,Elm,1,395.6,t +2017,Dunlin,2,1365.8,t +2018,Elm,2,1941.6,t +2018,Elm,1,384.5,t +2020,Dunlin,2,1382200,kg +2022,Dunlin,2,1216.3,t +2021,Alder,3,110.8,t +2019,Alder,3,121.1,t +2017,Elm,2,1912.2,t +2019,Dunlin,1,256.7,t +2019,Cedar,3,501500,kg +2021,Elm,1,387400,kg +2019,Cedar,1,436600,kg +2018,Cedar,3,509.7,t +2020,Cedar,2,942400,kg +2022,Cedar,1,358.5,t +2018,Elm,3,249.6,t +2021,Elm,2,1800.4,t +2017,Alder,2,334.8,t +2018,Alder,2,346.7,t +2022,Elm,2,1849.0,t +2021,Alder,2,294.1,t +2019,Dunlin,3,800.0,t +2020,Elm,3,233.5,t +2021,Elm,3,246500,kg +2022,Alder,2,264400,kg +2018,Dunlin,3,892.7,t +2022,Alder,3,104.8,t +2017,Dunlin,1,232.3,t +2017,Elm,3,240.6,t +2020,Elm,1,371.1,t +2019,Elm,3,259.2,t +2019,Elm,2,1869.3,t +2020,Dunlin,1,261.1,t +2018,Dunlin,1,243.2,t +2017,Cedar,1,499.5,t +2020,Dunlin,3,838.4,t +2018,Dunlin,2,1374.1,t +2021,Dunlin,2,1290.1,t +2021,Dunlin,1,233900,kg +2021,Dunlin,3,798.5,t +2017,Cedar,2,1132.5,t +2022,Alder,1,1292600,kg +2019,Cedar,2,952.1,t +2019,Alder,2,343.4,t +2020,Alder,1,1539100,kg +2021,Alder,1,1425900,kg +2022,Dunlin,3,735.8,t +2020,Alder,2,322.0,t +2020,Elm,2,1776.9,t +2020,Cedar,3,490.9,t +2017,Dunlin,3,920.8,t +2017,Cedar,3,538300,kg +2021,Cedar,1,376.0,t +2018,Alder,3,118.3,t +2019,Alder,1,1482.3,t +2022,Dunlin,1,247700,kg +2019,Elm,1,380000,kg diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..3a05d588b155195f888051aaef5f4258d3a9e22a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2022,14548 +2019,14929 +2020,14876 +2018,14492 +2017,14256 +2021,14731 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..64831ce8f702154b7f06547a9bd822a1ca298899 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Vessby Dairy Cooperative + +- Base year: 2017 +- Target year: 2031 +- Target: total emissions (scopes 1 to 3) 42 % below the base-year total. +- Output measure: thousand parcels delivered. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee7e9143f6258be022b535ccf3717abad82fb0b0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (thousand parcels delivered). `target.md` gives the base year and the reduction target of Vessby Dairy Cooperative (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2017"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2017. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2017. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2022 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2022, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2022 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..627758fe286b959614f1b51ec891d9438cd4be5a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 7 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..400934d39f3815bdbc13a5c883cc90ef95a9cfa2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 9335.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 654.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 9124.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 629.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -2.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -2.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 8809.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 590.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -3.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -5.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 8683.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 583.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -1.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -7.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 8433.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 572.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -2.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -9.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 8233.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 565.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -2.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -11.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 5414.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 313.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 7934.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0007/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..2fbe28acb67ef3de071b16dec962c23b7dfd91b0 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/emissions_ledger.csv @@ -0,0 +1,55 @@ +year,site,scope,amount,unit +2021,Dunlin,1,1787.8,t +2020,Dunlin,2,1931.6,t +2020,Elm,1,1569.3,t +2017,Alder,1,2395.3,t +2020,Alder,1,2089.2,t +2020,Elm,2,609.3,t +2018,Dunlin,1,1703.4,t +2021,Alder,3,2048100,kg +2022,Alder,1,2039300,kg +2018,Alder,2,1711.1,t +2017,Dunlin,1,1776200,kg +2018,Alder,1,2292100,kg +2021,Elm,3,2056.4,t +2019,Dunlin,2,1874800,kg +2018,Elm,3,2001.2,t +2017,Alder,2,1885.1,t +2020,Elm,3,1985.3,t +2018,Dunlin,2,1890.4,t +2018,Elm,2,590900,kg +2021,Elm,2,546.3,t +2022,Dunlin,3,938300,kg +2019,Dunlin,1,1687.6,t +2021,Dunlin,2,1958.0,t +2019,Alder,1,2263.9,t +2018,Alder,3,2062.9,t +2019,Elm,1,1737.6,t +2017,Elm,2,617500,kg +2017,Dunlin,3,1008.0,t +2020,Alder,3,2231400,kg +2022,Dunlin,1,1625200,kg +2019,Elm,2,602.2,t +2020,Dunlin,3,997300,kg +2022,Elm,1,1473600,kg +2019,Alder,3,2121100,kg +2019,Dunlin,3,1005.7,t +2018,Dunlin,3,965200,kg +2017,Elm,3,2232800,kg +2022,Dunlin,2,2059700,kg +2017,Dunlin,2,2096.6,t +2018,Elm,1,1856.7,t +2022,Alder,2,1668.4,t +2022,Alder,3,1955200,kg +2021,Alder,1,2037600,kg +2021,Dunlin,3,898.1,t +2020,Dunlin,1,1718.6,t +2021,Alder,2,1613.6,t +2019,Alder,2,1697600,kg +2022,Elm,3,2009.2,t +2017,Alder,3,2164.4,t +2019,Elm,3,2074.9,t +2017,Elm,1,1864.9,t +2021,Elm,1,1552.4,t +2022,Elm,2,504.7,t +2020,Alder,2,1596.5,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..4fb940b139df91a562168fe806782d6f11156592 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2020,83035 +2018,79946 +2019,82229 +2021,83887 +2017,75756 +2022,86073 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..85d422a155d024c9b1b56ddbe15757641ab4e1a2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Marrow Vale Housing + +- Base year: 2017 +- Target year: 2027 +- Target: total emissions (scopes 1 to 3) 25 % below the base-year total. +- Output measure: m2 of heated floor area. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29ceb845d8dd2a934213865bae0710e5c90ab201 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (m2 of heated floor area). `target.md` gives the base year and the reduction target of Marrow Vale Housing (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2017"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2017. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2017. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2022 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2022, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2022 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..093806c1a670f6be305d1a04cd717d4d0547d205 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 19 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8dbbb85b549f2fdd6c6578d0e02a47528dec4475 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 16040.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 211.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 15073.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 188.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -6.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -6.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 15065.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 183.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -0.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -6.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 14728.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 177.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -2.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -8.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 14498.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 172.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -9.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 14273.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 165.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -1.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -11.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 12030.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 448.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 14035.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0019/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..5d1fe6f9971e271de7fbc7dbcc3331ab6f1328a3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/emissions_ledger.csv @@ -0,0 +1,73 @@ +year,site,scope,amount,unit +2019,Cedar,3,1078.5,t +2019,Birch,1,807.1,t +2021,Dunlin,2,1351.2,t +2017,Alder,1,552100,kg +2021,Cedar,1,652.5,t +2018,Alder,2,1857.6,t +2018,Alder,3,1848.0,t +2019,Dunlin,3,910.4,t +2022,Birch,3,591.9,t +2021,Cedar,2,1183.8,t +2018,Cedar,3,1099800,kg +2017,Cedar,3,1205.3,t +2021,Dunlin,1,1539.9,t +2017,Birch,2,837.7,t +2019,Birch,3,623400,kg +2021,Alder,2,2022100,kg +2022,Dunlin,3,786.6,t +2021,Birch,3,621400,kg +2022,Cedar,3,933.8,t +2022,Birch,1,663.3,t +2018,Birch,1,865400,kg +2018,Cedar,1,690800,kg +2019,Dunlin,1,1749.2,t +2017,Alder,3,1812500,kg +2018,Alder,1,538.6,t +2019,Birch,2,789100,kg +2017,Dunlin,2,1437700,kg +2021,Alder,1,426200,kg +2018,Birch,2,762900,kg +2020,Alder,2,2062600,kg +2022,Alder,2,1940.3,t +2021,Birch,1,722.5,t +2021,Birch,2,791400,kg +2017,Birch,1,918.0,t +2020,Alder,1,458.0,t +2020,Alder,3,1863.2,t +2022,Dunlin,2,1237.0,t +2022,Alder,3,1855.6,t +2020,Dunlin,2,1354.0,t +2019,Alder,3,1895.9,t +2018,Cedar,2,1116.3,t +2022,Cedar,2,1122900,kg +2020,Cedar,2,1119.6,t +2017,Dunlin,3,1115.7,t +2021,Dunlin,3,841.3,t +2018,Birch,3,623.7,t +2020,Cedar,3,1001.0,t +2019,Cedar,2,1062.9,t +2020,Dunlin,1,1639.0,t +2017,Alder,2,2048.0,t +2019,Alder,1,485600,kg +2020,Dunlin,3,944.8,t +2020,Birch,1,756.3,t +2019,Alder,2,1961.7,t +2020,Birch,3,624.4,t +2019,Dunlin,2,1344.5,t +2020,Birch,2,797700,kg +2018,Dunlin,2,1288.5,t +2021,Cedar,3,943200,kg +2017,Birch,3,604.4,t +2017,Cedar,1,675.1,t +2022,Cedar,1,685.3,t +2018,Dunlin,3,998.8,t +2022,Alder,1,413.5,t +2021,Alder,3,1758.7,t +2020,Cedar,1,641100,kg +2017,Dunlin,1,1767500,kg +2019,Cedar,1,637400,kg +2017,Cedar,2,1195300,kg +2022,Dunlin,1,1507.9,t +2022,Birch,2,812000,kg +2018,Dunlin,1,1858.5,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..2ef4003e0039108267accf67a66c6b6c97acf138 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2018,137022 +2019,133765 +2020,135723 +2017,138989 +2022,135242 +2021,136401 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..db14e91b8e58a7d57c49ed79c4e5d7bdf6a2814c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Harlow Fold Logistics + +- Base year: 2017 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 50 % below the base-year total. +- Output measure: m2 of heated floor area. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e170539d32ec914f374fb8c8131ec6e98f1a63a9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (m2 of heated floor area). `target.md` gives the base year and the reduction target of Harlow Fold Logistics (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2017"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2017. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2017. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2022 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2022, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2022 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..70c57b22a3b714d07c6110ece31c3044d38b8590 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 31 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..02f8800b42a319656dcbd838f80b8cea526fc2e7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 14169.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 101.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 13548.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 98.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -4.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -4.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 13345.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 99.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -5.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 13261.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 97.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -0.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -6.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 12854.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 94.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -3.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -9.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 12550.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 92.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -2.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -11.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 7084.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 910.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 10949.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0031/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..d4d018331a0ab9520d655e0f1134daaa5bcb0eeb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/emissions_ledger.csv @@ -0,0 +1,73 @@ +year,site,scope,amount,unit +2016,Cedar,3,1219.8,t +2014,Cedar,1,1732900,kg +2016,Birch,3,966.4,t +2018,Birch,1,310500,kg +2018,Elm,3,937100,kg +2014,Elm,2,1432700,kg +2019,Birch,1,328.5,t +2019,Alder,2,1693.6,t +2017,Cedar,3,1242700,kg +2017,Alder,2,1842100,kg +2019,Birch,3,924700,kg +2017,Alder,1,493.3,t +2014,Alder,2,2105.2,t +2019,Elm,1,382.7,t +2018,Alder,1,502000,kg +2014,Birch,1,338.0,t +2019,Cedar,3,1035.9,t +2019,Elm,2,1239400,kg +2016,Elm,3,1090.9,t +2015,Alder,1,469500,kg +2014,Birch,3,1015000,kg +2015,Cedar,1,1773.0,t +2014,Alder,1,522000,kg +2016,Elm,1,414.3,t +2017,Elm,3,1023.4,t +2016,Birch,1,332300,kg +2017,Cedar,2,1243200,kg +2015,Cedar,3,1218700,kg +2016,Birch,2,1732.6,t +2017,Birch,3,939.4,t +2016,Alder,2,2021300,kg +2018,Birch,3,990.0,t +2015,Birch,1,340.9,t +2015,Birch,3,984500,kg +2015,Alder,3,2023.4,t +2018,Cedar,1,1651.0,t +2014,Cedar,2,1364900,kg +2015,Alder,2,1911200,kg +2017,Birch,1,343700,kg +2017,Birch,2,1656.0,t +2019,Cedar,1,1588600,kg +2014,Alder,3,2072200,kg +2015,Birch,2,1880.8,t +2018,Cedar,2,1301.8,t +2014,Cedar,3,1242.5,t +2017,Elm,2,1145.9,t +2016,Cedar,2,1340.3,t +2018,Elm,2,1189.9,t +2018,Alder,3,1800.1,t +2017,Elm,1,425.9,t +2015,Elm,2,1281600,kg +2019,Alder,1,475.2,t +2016,Cedar,1,1770.3,t +2018,Birch,2,1601.2,t +2019,Birch,2,1618.1,t +2018,Cedar,3,1109500,kg +2016,Elm,2,1206.8,t +2016,Alder,3,1874900,kg +2014,Birch,2,1942.0,t +2015,Cedar,2,1391.8,t +2014,Elm,1,422.6,t +2019,Elm,3,944.4,t +2014,Elm,3,1121200,kg +2017,Alder,3,1880600,kg +2019,Alder,3,1786.0,t +2018,Alder,2,1824.0,t +2016,Alder,1,477.8,t +2015,Elm,1,438.0,t +2015,Elm,3,1126.6,t +2019,Cedar,2,1379.6,t +2017,Cedar,1,1782.6,t +2018,Elm,1,401.7,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..7542360bef17b36cfa879d0beeadd3dc3f6a73a1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2016,20033 +2018,21405 +2015,19203 +2017,20643 +2019,21044 +2014,19504 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..36b40e7ede37b2253ee22c80c26b48afcd9713b2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Tarnwick Borough Council + +- Base year: 2014 +- Target year: 2027 +- Target: total emissions (scopes 1 to 3) 42 % below the base-year total. +- Output measure: tonnes of product. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9fb34eee955875d137946ef3f0e8de1be0511899 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (tonnes of product). `target.md` gives the base year and the reduction target of Tarnwick Borough Council (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2014"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2014. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2014. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2019 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2019, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2019 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..810324d62381d08459fe008abaa5b4d2202090c5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 43 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..0fd72b8a95c26fa0deb5e55dc6e7690c9b2be5df --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2014.total_t_co2e", + "type": "number", + "value": 15311.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2014.intensity_kg_per_unit", + "type": "number", + "value": 785.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2015.total_t_co2e", + "type": "number", + "value": 14840.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2015.intensity_kg_per_unit", + "type": "number", + "value": 772.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2015.change_vs_previous_percent", + "type": "number", + "value": -3.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2015.change_vs_base_percent", + "type": "number", + "value": -3.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 14447.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 721.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.change_vs_previous_percent", + "type": "number", + "value": -2.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.change_vs_base_percent", + "type": "number", + "value": -5.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 14018.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 679.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -3.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -8.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 13618.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 636.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -2.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -11.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 13396.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 636.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -12.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 8880.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 564.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 12837.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0043/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..418a134bf182c85305bedb5e3e82f7f5c647c469 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/emissions_ledger.csv @@ -0,0 +1,55 @@ +year,site,scope,amount,unit +2019,Cedar,3,849.5,t +2019,Birch,1,1776700,kg +2019,Birch,2,2213.7,t +2022,Cedar,1,1589.3,t +2018,Alder,2,660.3,t +2022,Birch,2,1985.1,t +2021,Birch,3,783500,kg +2019,Cedar,1,1874700,kg +2020,Cedar,1,1748.1,t +2019,Alder,1,901.9,t +2020,Birch,3,806.5,t +2021,Cedar,1,1559.8,t +2020,Cedar,2,2468.4,t +2019,Alder,2,655.6,t +2018,Birch,2,2368.2,t +2020,Alder,3,758.3,t +2022,Alder,2,595.9,t +2021,Birch,2,1943.6,t +2019,Cedar,2,2582700,kg +2018,Cedar,1,1988.6,t +2022,Alder,1,855.3,t +2023,Birch,3,742.9,t +2018,Alder,3,789400,kg +2023,Cedar,3,739000,kg +2022,Cedar,2,2177.9,t +2020,Cedar,3,793.9,t +2018,Birch,1,1927.8,t +2019,Alder,3,818.3,t +2023,Birch,1,1773.5,t +2021,Alder,2,581.3,t +2021,Cedar,2,2286400,kg +2020,Birch,1,1703.4,t +2018,Cedar,2,2579.4,t +2023,Alder,2,569.2,t +2020,Birch,2,1970.2,t +2022,Birch,3,715800,kg +2022,Cedar,3,798.1,t +2023,Alder,3,719.7,t +2021,Cedar,3,824.3,t +2018,Birch,3,989.2,t +2023,Alder,1,775.9,t +2022,Birch,1,1818100,kg +2023,Cedar,2,1951.6,t +2023,Birch,2,2088.3,t +2021,Alder,1,875.4,t +2021,Alder,3,771.8,t +2019,Birch,3,886.1,t +2021,Birch,1,1730.7,t +2020,Alder,1,945.5,t +2018,Alder,1,970.7,t +2018,Cedar,3,860.3,t +2023,Cedar,1,1594.3,t +2022,Alder,3,747.4,t +2020,Alder,2,630000,kg diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..5f7927e33ba727b5b07067736d19142a0827f5b1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2020,17016 +2021,17099 +2023,16778 +2022,17076 +2018,16337 +2019,16819 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..dca0845b160a6a85d00b7e3590e9d327724c1c5e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Vessby Dairy Cooperative + +- Base year: 2018 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 25 % below the base-year total. +- Output measure: thousand parcels delivered. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..102fea3996304eb418f70332eda83f1733369e4a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (thousand parcels delivered). `target.md` gives the base year and the reduction target of Vessby Dairy Cooperative (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2018"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2018. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2018. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2023 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2023, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2023 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ed4db7bbbc5c0fb49566f095233cbe58dbca07e9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 55 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..53bc61f08ea9e237582cae96a2d1430da7c12cc7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 13133.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 803.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 12559.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 746.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -4.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -4.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 11824.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 694.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -5.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -10.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 11356.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 664.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -4.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -13.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 11282.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 660.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -0.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -14.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.total_t_co2e", + "type": "number", + "value": 10954.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.intensity_kg_per_unit", + "type": "number", + "value": 652.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_previous_percent", + "type": "number", + "value": -2.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_base_percent", + "type": "number", + "value": -16.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 9850.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 220.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 11492.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": true, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0055/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..e8b2cee219165374658e58ad6ff0fa15daecfe47 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/emissions_ledger.csv @@ -0,0 +1,55 @@ +year,site,scope,amount,unit +2016,Dunlin,3,1035.4,t +2016,Dunlin,2,2355.3,t +2021,Cedar,1,635.2,t +2021,Cedar,2,555.3,t +2020,Cedar,2,535700,kg +2020,Dunlin,2,2035.0,t +2018,Dunlin,1,801.7,t +2021,Elm,1,237.3,t +2019,Dunlin,1,835.5,t +2019,Elm,3,2308.4,t +2021,Dunlin,2,1909.2,t +2020,Elm,1,231.6,t +2019,Elm,1,258.6,t +2017,Dunlin,3,1010.9,t +2019,Cedar,1,700.5,t +2018,Elm,3,2546.9,t +2021,Cedar,3,1081.2,t +2018,Elm,2,834.8,t +2021,Dunlin,3,942.4,t +2016,Dunlin,1,840000,kg +2016,Cedar,1,714.7,t +2016,Elm,2,940.7,t +2016,Elm,1,258400,kg +2019,Elm,2,877.5,t +2016,Cedar,3,1209000,kg +2020,Cedar,1,672.2,t +2017,Cedar,3,1154.7,t +2018,Cedar,3,1142.0,t +2021,Elm,3,2087.0,t +2018,Elm,1,252.8,t +2017,Cedar,2,546100,kg +2016,Cedar,2,565900,kg +2019,Cedar,2,565.2,t +2017,Dunlin,1,854.5,t +2020,Elm,2,854.4,t +2017,Elm,2,878.6,t +2018,Dunlin,2,2316.9,t +2017,Elm,1,260200,kg +2019,Dunlin,3,1006300,kg +2020,Elm,3,2062.5,t +2016,Elm,3,2792.9,t +2019,Dunlin,2,2103200,kg +2018,Cedar,1,682900,kg +2019,Cedar,3,1031.0,t +2020,Cedar,3,1024.4,t +2017,Elm,3,2579400,kg +2017,Dunlin,2,2417200,kg +2018,Cedar,2,555.8,t +2020,Dunlin,1,828500,kg +2018,Dunlin,3,1015.3,t +2021,Elm,2,901.8,t +2017,Cedar,1,699500,kg +2021,Dunlin,1,872800,kg +2020,Dunlin,3,929.5,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..3251d856bc94362dbaf2118fedc59510b2cfc0f1 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2019,36984 +2020,36516 +2016,35195 +2017,35131 +2021,37834 +2018,35669 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..a4251762f1b845506af5b3f09306592d337fa50c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Kestrel Joinery + +- Base year: 2016 +- Target year: 2030 +- Target: total emissions (scopes 1 to 3) 25 % below the base-year total. +- Output measure: tonnes of product. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0145b83eeb6631050a7f1641e2e1d4b1df818249 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (tonnes of product). `target.md` gives the base year and the reduction target of Kestrel Joinery (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2021 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2021, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2021 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5b2d9d02ca9c746bb6b5564199b51204a195db51 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 67 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f7a7633018d13ec60265d9fd56624373347b0200 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 10712.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 304.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 10401.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 296.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -2.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -2.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 10149.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 284.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -2.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 9686.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 261.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -4.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -9.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 9173.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 251.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -14.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 9222.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 243.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": 0.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -13.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 8034.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 132.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 9755.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": true, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0067/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..c2fb8f3a4eb0a52c90df63bfbba0982ac43c88f7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/emissions_ledger.csv @@ -0,0 +1,55 @@ +year,site,scope,amount,unit +2021,Dunlin,1,2340000,kg +2020,Dunlin,1,2268.9,t +2016,Dunlin,2,2568.6,t +2020,Alder,3,1288.6,t +2016,Birch,2,94.7,t +2018,Dunlin,1,2567300,kg +2020,Alder,2,1211.4,t +2019,Dunlin,2,2715.0,t +2016,Alder,1,438.1,t +2021,Birch,2,96.8,t +2016,Birch,3,356.4,t +2018,Birch,2,96.9,t +2018,Dunlin,3,1830.0,t +2017,Dunlin,2,2628.9,t +2017,Birch,2,94.3,t +2021,Dunlin,2,2850.3,t +2019,Dunlin,3,1934200,kg +2016,Dunlin,3,1951100,kg +2019,Alder,3,1231600,kg +2017,Birch,1,2322.4,t +2021,Alder,1,395.9,t +2018,Alder,3,1282.6,t +2019,Alder,2,1294800,kg +2020,Birch,1,2394.8,t +2021,Birch,3,319600,kg +2017,Alder,3,1346.8,t +2020,Birch,2,97.3,t +2020,Dunlin,3,1815.6,t +2017,Birch,3,350.0,t +2021,Dunlin,3,1815.7,t +2018,Dunlin,2,2784.5,t +2017,Alder,2,1332.5,t +2016,Dunlin,1,2846.1,t +2021,Alder,3,1331100,kg +2021,Birch,1,2392.4,t +2020,Alder,1,391.4,t +2019,Birch,1,2315.9,t +2016,Alder,3,1296.0,t +2018,Birch,1,2338.4,t +2017,Dunlin,3,1758.8,t +2016,Alder,2,1408.2,t +2018,Alder,2,1295.5,t +2017,Alder,1,405.3,t +2019,Dunlin,1,2525800,kg +2020,Dunlin,2,2706300,kg +2021,Alder,2,1092900,kg +2020,Birch,3,330500,kg +2016,Birch,1,2578500,kg +2019,Birch,3,366100,kg +2019,Alder,1,388.5,t +2017,Dunlin,1,2788.4,t +2019,Birch,2,99.0,t +2018,Birch,3,362.0,t +2018,Alder,1,373.3,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..a2a24047ff8ca2c66615b700a385715036310958 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/output.csv @@ -0,0 +1,7 @@ +year,output +2019,82411 +2021,83612 +2017,81114 +2018,79797 +2020,81883 +2016,78898 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..2cde57b4f3dfb6e88e4c37988cf9adeccdf68d88 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/environment/workdir/target.md @@ -0,0 +1,6 @@ +# Emissions target: Brantholm Municipality + +- Base year: 2016 +- Target year: 2030 +- Target: total emissions (scopes 1 to 3) 30 % below the base-year total. +- Output measure: residents. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c21670ce715ab23a5ef72619810ff9fc9e22ac89 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/instruction.md @@ -0,0 +1,17 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each year's output (residents). `target.md` gives the base year and the reduction target of Brantholm Municipality (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2021 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2021, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2021 total is at or below `linear_path_latest_t`, otherwise false. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b2c1b0ce3039c1f796315fe95e2f13867aa94adc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 79 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e8d27ed3ea42549f90bb9d1fa1f078086d2681e7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/checks.json @@ -0,0 +1,183 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 13537.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 171.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 13027.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 160.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -3.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -3.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 12930.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 162.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -0.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -4.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 12870.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 156.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -0.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -4.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 12504.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 152.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -2.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -7.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 12634.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 151.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": 1.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -6.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 9476.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 350.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 12087.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d2-t0079/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..37d83c8dfac366513605ff63682ad3c8cc42b5af --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/emissions_ledger.csv @@ -0,0 +1,79 @@ +year,site,scope,amount,unit +2018,Elm,3,1007.1,t +2018,Elm,2,1249.4,t +2017,Cedar,1,618.8,t +2016,Alder,1,1756.3,t +2021,Birch,2,1279.1,t +2021,Elm,3,995100,kg +2020,Elm,2,1155.0,t +2018,Elm,1,794.9,t +2017,Birch,3,548000,kg +2020,Cedar,2,609.1,t +2017,Alder,3,1709.6,t +2018,Alder,1,1792.4,t +2016,Cedar,1,623.3,t +2022,Elm,3,1045100,kg +2022,Birch,1,1829.0,t +2021,Elm,2,1074.1,t +2016,Birch,1,2069.4,t +2022,Alder,2,729.9,t +2016,Elm,3,984.0,t +2018,Alder,3,1607.7,t +2021,Birch,3,497.1,t +2019,Cedar,1,607600,kg +2022,Elm,2,1026.3,t +2018,Birch,2,1304000,kg +2020,Cedar,3,1760200,kg +2021,Birch,1,1730.1,t +2019,Elm,1,827500,kg +2019,Cedar,2,662.7,t +2019,Elm,3,1021.2,t +2018,Cedar,3,1740.1,t +2021,Alder,3,1575300,kg +2020,Elm,3,945400,kg +2020,Cedar,1,582.9,t +2019,Elm,2,1202.2,t +2016,Birch,2,1283600,kg +2018,Cedar,1,620.8,t +2019,Birch,3,511.0,t +2018,Alder,2,765.4,t +2021,Elm,1,813.4,t +2017,Alder,2,820100,kg +2020,Alder,1,1838.7,t +2020,Birch,3,488300,kg +2016,Birch,3,566.3,t +2016,Cedar,3,1700.7,t +2020,Birch,2,1251000,kg +2016,Cedar,2,663.8,t +2016,Elm,2,1205.3,t +2018,Birch,1,1950300,kg +2022,Elm,1,822.2,t +2016,Alder,3,1649.9,t +2017,Alder,1,1770.9,t +2022,Birch,2,1171300,kg +2020,Birch,1,1656000,kg +2017,Cedar,3,1795700,kg +2020,Elm,1,819.1,t +2019,Alder,3,1682900,kg +2022,Alder,1,1663.0,t +2021,Alder,2,799.1,t +2022,Alder,3,1454500,kg +2017,Elm,3,994.1,t +2017,Cedar,2,700600,kg +2018,Cedar,2,660.7,t +2017,Birch,2,1268.9,t +2019,Alder,2,748.9,t +2019,Birch,2,1248.5,t +2017,Elm,2,1273.8,t +2018,Birch,3,567900,kg +2019,Cedar,3,1724.0,t +2016,Elm,1,853.3,t +2017,Elm,1,843800,kg +2016,Alder,2,779.7,t +2021,Alder,1,1648300,kg +2019,Birch,1,1778200,kg +2017,Birch,1,2176.3,t +2019,Alder,1,1887.1,t +2020,Alder,3,1686500,kg +2020,Alder,2,766.9,t +2022,Birch,3,490600,kg diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..c275b5ecb6b4e0d5f6a81c336c3699c9f699e739 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/output.csv @@ -0,0 +1,27 @@ +year,site,output +2018,Birch,221 +2019,Birch,223 +2020,Elm,2518 +2021,Elm,2538 +2016,Elm,2503 +2020,Alder,310 +2019,Cedar,1167 +2017,Elm,2541 +2021,Alder,308 +2017,Alder,311 +2020,Birch,235 +2022,Elm,2421 +2018,Cedar,1133 +2017,Birch,222 +2017,Cedar,1107 +2019,Elm,2633 +2016,Alder,319 +2016,Birch,226 +2022,Alder,293 +2016,Cedar,1145 +2022,Birch,231 +2019,Alder,309 +2020,Cedar,1117 +2018,Alder,321 +2021,Birch,225 +2018,Elm,2472 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..a7c61344b50f3c7a158853a1794c35b567a8c170 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Lindqvist Castings + +- Base year: 2016 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 50 % below the base-year total. +- Output measure: thousand parcels delivered. +- Divested site: Cedar (sold in 2021) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c3df6fa37c77b73060ef263bec8d123ed95e128 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (thousand parcels delivered); a year's output is the sum over sites. Site Cedar was sold in 2021. Under the base-year recalculation policy in `target.md`, leave site Cedar out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Lindqvist Castings (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2022 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2022, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2022 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2022 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..02cd16cee44786aeb830c36a80e721395a8cb72c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "eval"] +isced_f = "0521" +family = "time-series" +split = "eval" +seed = 10011 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cd1729a03c83f441324ec96be28c89f5555d8fe7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 11147.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 3657.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 11405.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 3710.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": 2.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": 2.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 11039.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 3662.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -3.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -1.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 10907.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 3446.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -2.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 10606.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 3462.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -2.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -4.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 10411.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 3390.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -1.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -6.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 10231.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 3474.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -1.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -8.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 5573.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 776.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 8360.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 9.63, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0011/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..aa43562ef43e259617409492391c35881a960f27 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/emissions_ledger.csv @@ -0,0 +1,58 @@ +year,site,scope,amount,unit +2021,Dunlin,1,89400,kg +2018,Dunlin,2,2098400,kg +2020,Birch,1,312.9,t +2024,Cedar,1,1384.5,t +2020,Cedar,3,2246.9,t +2018,Birch,3,2711.1,t +2023,Cedar,3,1974.4,t +2018,Dunlin,3,1835.0,t +2022,Cedar,1,1476.7,t +2019,Cedar,1,1725.6,t +2020,Dunlin,2,2029.0,t +2020,Dunlin,1,99100,kg +2018,Dunlin,1,105.6,t +2024,Cedar,3,2080.5,t +2021,Birch,1,305.6,t +2022,Dunlin,3,1568.5,t +2019,Cedar,2,996.0,t +2024,Cedar,2,822200,kg +2023,Cedar,1,1426.8,t +2023,Dunlin,2,1858.9,t +2019,Dunlin,1,108.1,t +2019,Cedar,3,2269900,kg +2020,Cedar,1,1656.5,t +2024,Dunlin,1,87500,kg +2019,Birch,3,2662.4,t +2023,Cedar,2,808700,kg +2022,Birch,1,296.2,t +2022,Cedar,3,1873.1,t +2020,Cedar,2,910.7,t +2018,Cedar,1,1794.1,t +2018,Birch,1,321.8,t +2021,Cedar,3,2067.0,t +2022,Birch,3,2347.4,t +2018,Birch,2,1436.7,t +2022,Dunlin,2,1912.6,t +2024,Dunlin,3,1461200,kg +2020,Dunlin,3,1865.4,t +2023,Dunlin,3,1476.8,t +2020,Birch,2,1294100,kg +2020,Birch,3,2701.5,t +2022,Dunlin,1,91.2,t +2019,Birch,1,331800,kg +2021,Birch,2,1346400,kg +2021,Cedar,1,1532800,kg +2024,Dunlin,2,1743600,kg +2018,Cedar,2,971.4,t +2021,Birch,3,2600.3,t +2018,Cedar,3,2144.8,t +2022,Cedar,2,780.5,t +2019,Dunlin,2,2077900,kg +2021,Dunlin,2,1979.4,t +2019,Dunlin,3,1808.3,t +2023,Dunlin,1,85.7,t +2021,Cedar,2,858.8,t +2021,Dunlin,3,1703600,kg +2019,Birch,2,1336.7,t +2022,Birch,2,1212.3,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..d8ed13eabb276b7a0c355cba07dc456f6cb303e7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/output.csv @@ -0,0 +1,20 @@ +year,site,output +2019,Cedar,97116 +2020,Dunlin,30698 +2023,Dunlin,29374 +2024,Dunlin,29862 +2021,Cedar,95595 +2024,Cedar,101692 +2020,Birch,60766 +2018,Dunlin,30257 +2022,Birch,61736 +2021,Birch,62108 +2023,Cedar,96208 +2019,Birch,61277 +2022,Dunlin,30707 +2018,Birch,63786 +2020,Cedar,93980 +2019,Dunlin,30519 +2022,Cedar,96836 +2021,Dunlin,30716 +2018,Cedar,92398 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..825454f5f9a3d2534331b4482b9a8a08a1eae901 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Vessby Dairy Cooperative + +- Base year: 2018 +- Target year: 2033 +- Target: total emissions (scopes 1 to 3) 42 % below the base-year total. +- Output measure: m2 of heated floor area. +- Divested site: Birch (sold in 2023) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dcaf719b47fc6dfbc13de299767d02d6218f441d --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (m2 of heated floor area); a year's output is the sum over sites. Site Birch was sold in 2023. Under the base-year recalculation policy in `target.md`, leave site Birch out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Vessby Dairy Cooperative (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2018"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2018. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2018. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2024 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2024, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2024 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2024 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d97954c5d3f05bbe17b232871daf0683718aca03 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "eval"] +isced_f = "0521" +family = "time-series" +split = "eval" +seed = 10023 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..3559c36c543994dcaaff37b04946ab69730025a4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 8949.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 73.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 8985.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 70.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": 0.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": 0.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 8807.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 70.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -2.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 8231.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 65.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -6.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -8.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 7702.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 60.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -6.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -13.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.total_t_co2e", + "type": "number", + "value": 7631.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.intensity_kg_per_unit", + "type": "number", + "value": 60.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_previous_percent", + "type": "number", + "value": -0.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_base_percent", + "type": "number", + "value": -14.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2024.total_t_co2e", + "type": "number", + "value": 7579.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2024.intensity_kg_per_unit", + "type": "number", + "value": 57.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2024.change_vs_previous_percent", + "type": "number", + "value": -0.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2024.change_vs_base_percent", + "type": "number", + "value": -15.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 5190.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 265.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 7445.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 4.12, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-e0023/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..8112e4fe59f818d06ccf91285459ddbd707704ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/emissions_ledger.csv @@ -0,0 +1,79 @@ +year,site,scope,amount,unit +2020,Cedar,2,1895.9,t +2018,Alder,1,2277.7,t +2016,Cedar,3,1618.5,t +2019,Cedar,2,2030.0,t +2019,Alder,3,1755.5,t +2017,Cedar,1,1437.2,t +2020,Birch,2,1458.8,t +2016,Elm,3,765.7,t +2017,Cedar,3,1540.1,t +2019,Birch,2,1478.8,t +2018,Elm,2,678.0,t +2020,Elm,1,2061.7,t +2017,Birch,1,799.8,t +2020,Elm,2,687.1,t +2016,Birch,2,1726.1,t +2017,Alder,3,1809000,kg +2017,Birch,2,1563.9,t +2018,Cedar,3,1397000,kg +2016,Alder,2,595.5,t +2022,Elm,1,2272.3,t +2022,Cedar,3,1437500,kg +2016,Birch,3,1538.3,t +2021,Alder,1,2149.4,t +2016,Elm,1,1927.5,t +2018,Birch,3,1613900,kg +2019,Cedar,3,1429.7,t +2017,Elm,3,722.0,t +2020,Alder,3,1625.1,t +2021,Elm,2,660500,kg +2019,Alder,1,2194.3,t +2018,Birch,2,1444.4,t +2020,Birch,1,724.4,t +2021,Elm,1,2162500,kg +2017,Alder,2,559200,kg +2016,Alder,1,2147400,kg +2019,Elm,2,658.2,t +2016,Birch,1,771.1,t +2021,Cedar,3,1533.0,t +2019,Birch,1,795.9,t +2021,Cedar,1,1358.8,t +2017,Cedar,2,1862.4,t +2018,Birch,1,774.4,t +2022,Cedar,1,1269.4,t +2019,Elm,1,1983000,kg +2016,Elm,2,766.3,t +2022,Alder,3,1538100,kg +2019,Elm,3,737.3,t +2021,Alder,2,505.7,t +2020,Cedar,3,1449.7,t +2022,Elm,3,675.9,t +2018,Alder,2,572.0,t +2018,Cedar,1,1291.1,t +2018,Elm,3,723.5,t +2018,Elm,1,2146.0,t +2022,Alder,1,2142.4,t +2016,Cedar,1,1504100,kg +2022,Elm,2,656.5,t +2022,Cedar,2,1974.8,t +2021,Elm,3,714000,kg +2020,Cedar,1,1379800,kg +2020,Birch,3,1534.7,t +2016,Alder,3,1805100,kg +2020,Alder,1,2080900,kg +2019,Alder,2,532.6,t +2021,Cedar,2,1957.4,t +2018,Cedar,2,1927.1,t +2017,Elm,2,686.3,t +2018,Alder,3,1762.0,t +2019,Cedar,1,1305.7,t +2021,Alder,3,1619.5,t +2019,Birch,3,1525.2,t +2017,Birch,3,1529.6,t +2020,Elm,3,759100,kg +2020,Alder,2,518300,kg +2016,Cedar,2,1956.1,t +2017,Elm,1,2026.1,t +2022,Alder,2,494.9,t +2017,Alder,1,2239000,kg diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..44433e0a1c4e3c8ffff8c17ee568d85101add844 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/output.csv @@ -0,0 +1,27 @@ +year,site,output +2020,Birch,5208 +2017,Elm,16941 +2021,Alder,7985 +2019,Birch,5215 +2018,Elm,17585 +2019,Cedar,7567 +2020,Alder,8224 +2019,Alder,8614 +2022,Cedar,7725 +2020,Cedar,7665 +2022,Alder,8388 +2019,Elm,16823 +2016,Alder,9466 +2018,Cedar,7838 +2020,Elm,16124 +2017,Birch,4859 +2022,Elm,17341 +2018,Alder,9009 +2018,Birch,4999 +2017,Cedar,7513 +2021,Cedar,7426 +2021,Elm,17205 +2016,Cedar,7046 +2016,Elm,15914 +2016,Birch,5000 +2017,Alder,9017 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..9a9eb99c13c0ffa27d4bde063c9a5b31871695b9 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Kestrel Joinery + +- Base year: 2016 +- Target year: 2031 +- Target: total emissions (scopes 1 to 3) 45 % below the base-year total. +- Output measure: tonnes of product. +- Divested site: Birch (sold in 2021) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec1c045fefd976b24614222b651a20ac6840b49a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (tonnes of product); a year's output is the sum over sites. Site Birch was sold in 2021. Under the base-year recalculation policy in `target.md`, leave site Birch out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Kestrel Joinery (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2022 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2022, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2022 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2022 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7f67462c139e3e71ad82299d032079d0be085b64 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 11 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6eeb516f8018efa3f62230b61e2cd9ef60cdbf21 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 13086.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 403.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 12881.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 384.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 12774.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 371.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -0.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -2.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 12626.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 382.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -3.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 12457.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 389.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -1.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -4.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 12660.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 388.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": 1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -3.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 12461.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 372.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -1.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -4.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 7197.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 584.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 10730.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 5.92, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0011/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..ff224b4d5517e9722b38b833cf07c8d03c6a43f2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/emissions_ledger.csv @@ -0,0 +1,58 @@ +year,site,scope,amount,unit +2022,Birch,3,1604700,kg +2021,Birch,1,600700,kg +2023,Birch,1,617.4,t +2022,Birch,1,586100,kg +2021,Cedar,3,1229.5,t +2018,Alder,1,1678900,kg +2021,Cedar,2,1712.5,t +2020,Cedar,3,1242.5,t +2020,Birch,3,1562500,kg +2017,Cedar,1,592.5,t +2021,Birch,2,1005.7,t +2018,Cedar,1,551.7,t +2022,Cedar,2,1739.0,t +2017,Alder,1,1679.1,t +2019,Cedar,3,1299900,kg +2019,Cedar,1,532.8,t +2017,Cedar,3,1395.8,t +2020,Alder,3,466.8,t +2023,Birch,3,1532.7,t +2017,Birch,1,708.4,t +2018,Cedar,3,1310.8,t +2023,Cedar,2,1752400,kg +2019,Birch,1,625300,kg +2019,Alder,2,2685.8,t +2021,Cedar,1,565.3,t +2019,Birch,3,1688800,kg +2018,Alder,2,2727.3,t +2021,Alder,2,2916.2,t +2019,Cedar,2,1720.1,t +2017,Birch,2,1054300,kg +2023,Cedar,1,543.7,t +2021,Alder,3,469.8,t +2017,Birch,3,1903.1,t +2022,Cedar,1,587.6,t +2018,Birch,1,698000,kg +2017,Cedar,2,1752600,kg +2020,Alder,2,2756600,kg +2019,Birch,2,929.9,t +2021,Alder,1,1403300,kg +2019,Alder,3,451500,kg +2023,Birch,2,1046.6,t +2020,Cedar,2,1664.5,t +2023,Cedar,3,1213.2,t +2022,Birch,2,1065.7,t +2021,Birch,3,1540600,kg +2018,Birch,2,947.2,t +2017,Alder,3,489800,kg +2020,Birch,1,583.6,t +2020,Alder,1,1521.7,t +2020,Birch,2,965.4,t +2019,Alder,1,1502.4,t +2022,Cedar,3,1166900,kg +2018,Birch,3,1886.5,t +2017,Alder,2,2911.6,t +2018,Alder,3,477.6,t +2018,Cedar,2,1641.0,t +2020,Cedar,1,534.6,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..5242546273a14069cf674b1527c43c44f97534cb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/output.csv @@ -0,0 +1,20 @@ +year,site,output +2021,Birch,23767 +2020,Alder,89025 +2023,Cedar,79172 +2017,Cedar,80157 +2022,Cedar,79558 +2018,Cedar,77774 +2023,Birch,23280 +2017,Birch,24222 +2017,Alder,90697 +2021,Alder,87584 +2021,Cedar,80650 +2020,Birch,22650 +2022,Birch,22856 +2019,Birch,23139 +2019,Cedar,80037 +2018,Birch,23817 +2019,Alder,88550 +2020,Cedar,84232 +2018,Alder,92106 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..17e2734c7d8352bcdbdc6f9c3b0b35d43589896a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Vessby Dairy Cooperative + +- Base year: 2017 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 30 % below the base-year total. +- Output measure: m2 of heated floor area. +- Divested site: Alder (sold in 2022) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c4f626f57aaf7189827764b931b163cb56927ff4 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (m2 of heated floor area); a year's output is the sum over sites. Site Alder was sold in 2022. Under the base-year recalculation policy in `target.md`, leave site Alder out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Vessby Dairy Cooperative (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2017"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2017. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2017. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2023 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2023, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2023 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2023 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..422045baf9d99ebf10ef48b08381b2e4d0db922f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 23 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a491b2a47971b110c75c280407233207f1d5d334 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 7406.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 71.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 7035.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 69.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -5.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -5.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 6796.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 65.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -3.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -8.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 6553.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 61.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -3.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -11.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 6654.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 63.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": 1.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -10.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 6750.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 65.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": 1.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -8.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.total_t_co2e", + "type": "number", + "value": 6706.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.intensity_kg_per_unit", + "type": "number", + "value": 65.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_previous_percent", + "type": "number", + "value": -0.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_base_percent", + "type": "number", + "value": -9.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 5184.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 304.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 6194.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 5.02, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0023/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..3dcb241f31231f186b40085c998ef897648adf16 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/emissions_ledger.csv @@ -0,0 +1,79 @@ +year,site,scope,amount,unit +2015,Birch,3,1815.8,t +2018,Cedar,2,1261.1,t +2017,Birch,2,434200,kg +2020,Elm,2,982.9,t +2016,Cedar,3,638400,kg +2017,Cedar,1,401.6,t +2019,Elm,1,286.7,t +2015,Cedar,2,1169000,kg +2018,Birch,3,1817.1,t +2019,Birch,1,759.8,t +2015,Cedar,3,603400,kg +2020,Birch,3,1927.1,t +2021,Birch,3,1962200,kg +2017,Alder,2,801.5,t +2019,Elm,3,1228.8,t +2017,Cedar,3,631.8,t +2018,Alder,1,88800,kg +2016,Cedar,1,417.6,t +2018,Cedar,3,575.1,t +2019,Elm,2,979.9,t +2018,Birch,2,420.8,t +2017,Elm,1,273.4,t +2020,Alder,3,1009.5,t +2018,Elm,3,1235.5,t +2016,Birch,2,469.6,t +2017,Alder,3,941.4,t +2019,Alder,2,746.6,t +2016,Birch,3,1892.5,t +2016,Cedar,2,1227600,kg +2016,Alder,2,789400,kg +2019,Cedar,1,356900,kg +2020,Birch,1,741.8,t +2021,Elm,1,253.8,t +2015,Birch,2,449100,kg +2019,Cedar,2,1295.0,t +2020,Birch,2,372600,kg +2015,Birch,1,915300,kg +2016,Alder,3,915.8,t +2021,Birch,1,776.1,t +2015,Alder,3,945500,kg +2016,Alder,1,89.2,t +2015,Elm,1,272600,kg +2017,Birch,1,910100,kg +2017,Alder,1,91.7,t +2021,Elm,2,942000,kg +2016,Elm,1,288.3,t +2016,Elm,2,1194.3,t +2021,Alder,3,944600,kg +2021,Alder,2,728100,kg +2015,Alder,2,809500,kg +2018,Cedar,1,357.9,t +2021,Birch,2,335.6,t +2017,Elm,2,1092700,kg +2019,Cedar,3,512.4,t +2021,Elm,3,1295900,kg +2018,Elm,2,1041.2,t +2018,Elm,1,275000,kg +2015,Alder,1,88.4,t +2019,Birch,3,1918.1,t +2019,Alder,1,79800,kg +2021,Alder,1,76.2,t +2018,Alder,2,756.2,t +2018,Alder,3,977.4,t +2017,Cedar,2,1192.5,t +2015,Elm,3,1523.7,t +2015,Cedar,1,418.0,t +2020,Alder,2,727.3,t +2020,Alder,1,77.0,t +2016,Elm,3,1390.5,t +2020,Elm,3,1276.6,t +2017,Elm,3,1238.4,t +2018,Birch,1,833100,kg +2020,Elm,1,258.1,t +2015,Elm,2,1192.4,t +2017,Birch,3,1808.0,t +2016,Birch,1,884400,kg +2019,Alder,3,973.8,t +2019,Birch,2,389.9,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..dc14348479338c21da989af754604d2cb23a8071 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/output.csv @@ -0,0 +1,27 @@ +year,site,output +2015,Birch,2085 +2018,Cedar,8957 +2016,Elm,5035 +2017,Cedar,8434 +2015,Cedar,8408 +2016,Alder,9635 +2019,Birch,2286 +2020,Elm,6133 +2017,Alder,9973 +2021,Birch,2254 +2020,Alder,10916 +2016,Cedar,8522 +2021,Elm,6023 +2018,Alder,10369 +2021,Alder,10646 +2017,Elm,5335 +2019,Elm,5747 +2015,Alder,9212 +2018,Birch,2201 +2015,Elm,4822 +2019,Cedar,8537 +2020,Birch,2230 +2019,Alder,10445 +2017,Birch,2240 +2016,Birch,2132 +2018,Elm,5516 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..e68c9acc72cd9ee28973a6a5a1cbadd4a7761b04 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Vessby Dairy Cooperative + +- Base year: 2015 +- Target year: 2029 +- Target: total emissions (scopes 1 to 3) 25 % below the base-year total. +- Output measure: tonnes of product. +- Divested site: Cedar (sold in 2020) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e28e88cd1a04a9b68ea9f378bf67e1c90ea01b33 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (tonnes of product); a year's output is the sum over sites. Site Cedar was sold in 2020. Under the base-year recalculation policy in `target.md`, leave site Cedar out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Vessby Dairy Cooperative (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2015"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2015. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2015. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2021 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2021, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2021 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2021 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0735da59ef0021bd44f4d2ee166f2b5e7169404f --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 35 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..05effb8723d240077ca0aeb551be52a5653101d6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2015.total_t_co2e", + "type": "number", + "value": 8012.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2015.intensity_kg_per_unit", + "type": "number", + "value": 497.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 7914.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 471.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.change_vs_previous_percent", + "type": "number", + "value": -1.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.change_vs_base_percent", + "type": "number", + "value": -1.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 7591.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 432.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -4.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 7445.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 411.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -1.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -7.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 7363.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 398.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -8.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 7372.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 382.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": 0.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -8.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 7314.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 386.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -0.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -8.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 6009.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 163.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 7153.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 2.43, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0035/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..095ea6d04a4c40fad39f85973542ca35ea203a09 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/emissions_ledger.csv @@ -0,0 +1,79 @@ +year,site,scope,amount,unit +2018,Elm,3,1170.3,t +2020,Dunlin,2,1661.4,t +2020,Cedar,3,1847800,kg +2023,Alder,3,2231.8,t +2023,Elm,3,986500,kg +2021,Cedar,2,640.0,t +2021,Elm,2,200.3,t +2017,Cedar,2,742.6,t +2017,Elm,1,442.8,t +2017,Dunlin,3,821.4,t +2019,Dunlin,2,1741.2,t +2020,Cedar,1,1802.1,t +2017,Elm,3,1200.7,t +2019,Dunlin,1,1676000,kg +2023,Elm,2,181.6,t +2022,Cedar,3,1664000,kg +2019,Cedar,2,627800,kg +2018,Dunlin,1,1874400,kg +2021,Dunlin,3,730.5,t +2023,Elm,1,361.2,t +2020,Dunlin,1,1592.8,t +2021,Dunlin,2,1666300,kg +2023,Cedar,3,1523.5,t +2022,Cedar,1,1774.9,t +2020,Elm,2,210800,kg +2020,Dunlin,3,748.7,t +2019,Elm,3,1105.2,t +2017,Cedar,3,1662.9,t +2023,Cedar,1,1621.2,t +2018,Dunlin,2,1941200,kg +2022,Alder,3,2106600,kg +2023,Alder,1,1875.8,t +2018,Elm,2,199.8,t +2021,Cedar,3,1731.8,t +2018,Alder,1,1948.3,t +2023,Alder,2,548.3,t +2019,Alder,2,543.9,t +2022,Cedar,2,630.5,t +2017,Alder,3,2179.9,t +2019,Cedar,1,1742.7,t +2023,Cedar,2,651.5,t +2021,Cedar,1,1906.7,t +2022,Elm,3,1068000,kg +2018,Elm,1,413.7,t +2018,Cedar,2,687.1,t +2022,Elm,1,360.8,t +2017,Cedar,1,1876700,kg +2017,Dunlin,1,1781.4,t +2019,Elm,2,204.5,t +2021,Alder,2,569.0,t +2021,Alder,3,2342.4,t +2020,Elm,1,401100,kg +2019,Dunlin,3,776.8,t +2017,Alder,2,582.4,t +2017,Dunlin,2,1851400,kg +2021,Alder,1,1953.2,t +2021,Dunlin,1,1547.2,t +2020,Alder,2,562900,kg +2020,Elm,3,1166900,kg +2020,Alder,3,2245.0,t +2018,Alder,3,2211.3,t +2019,Elm,1,416.2,t +2019,Alder,3,2227300,kg +2020,Cedar,2,615.8,t +2018,Cedar,3,1695300,kg +2018,Alder,2,586.2,t +2020,Alder,1,1910.3,t +2022,Elm,2,197000,kg +2018,Cedar,1,1834500,kg +2021,Elm,1,386.7,t +2017,Alder,1,1924400,kg +2019,Cedar,3,1786.3,t +2021,Elm,3,1166100,kg +2022,Alder,2,536800,kg +2018,Dunlin,3,862400,kg +2017,Elm,2,196.4,t +2019,Alder,1,1886.3,t +2022,Alder,1,2031200,kg diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..12f4cb57f866f08da60d140fe2e6724860f7134b --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/output.csv @@ -0,0 +1,27 @@ +year,site,output +2021,Elm,34284 +2017,Cedar,46964 +2018,Cedar,48850 +2017,Dunlin,10910 +2020,Cedar,51632 +2022,Cedar,54879 +2021,Cedar,52738 +2023,Alder,36839 +2019,Cedar,49553 +2020,Elm,32334 +2022,Elm,36509 +2021,Alder,38757 +2019,Alder,34692 +2018,Alder,35403 +2018,Dunlin,10998 +2023,Elm,37287 +2017,Elm,32716 +2022,Alder,37335 +2021,Dunlin,11818 +2019,Elm,33822 +2017,Alder,34217 +2020,Alder,36345 +2018,Elm,32192 +2023,Cedar,57647 +2019,Dunlin,10937 +2020,Dunlin,11664 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..46029c7f240e85c64e745e337e559379503cb081 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Tarnwick Borough Council + +- Base year: 2017 +- Target year: 2027 +- Target: total emissions (scopes 1 to 3) 42 % below the base-year total. +- Output measure: m2 of heated floor area. +- Divested site: Dunlin (sold in 2022) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ddacd231230ba62d9658fcff683de1db2324f6d2 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (m2 of heated floor area); a year's output is the sum over sites. Site Dunlin was sold in 2022. Under the base-year recalculation policy in `target.md`, leave site Dunlin out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Tarnwick Borough Council (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2017"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2017. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2017. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2023 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2023, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2023 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2023 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e3d35ca4f486cd73e79d25d35949853433189830 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 47 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ac9b981dc5ef68b1e9dc2aed095b6de4c563caf6 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 10808.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 94.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 10746.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 92.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -0.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -0.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 10540.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 89.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -2.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 10762.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 89.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": 2.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -0.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 10896.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 86.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": 1.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": 0.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 10369.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 80.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -4.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -4.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.total_t_co2e", + "type": "number", + "value": 9981.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.intensity_kg_per_unit", + "type": "number", + "value": 75.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_previous_percent", + "type": "number", + "value": -3.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_base_percent", + "type": "number", + "value": -7.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 6269.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 928.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 8085.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 10.98, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0047/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..053a38e6fee81a9245839610c99c53b68acebb60 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/emissions_ledger.csv @@ -0,0 +1,58 @@ +year,site,scope,amount,unit +2021,Dunlin,2,2643000,kg +2020,Dunlin,2,2588.4,t +2019,Alder,1,1918.5,t +2021,Birch,3,512.9,t +2022,Birch,3,508.8,t +2021,Alder,2,1488.5,t +2022,Alder,2,1368.7,t +2022,Alder,3,1396.5,t +2018,Birch,1,2379.1,t +2022,Birch,1,2515900,kg +2018,Dunlin,3,1958.3,t +2021,Alder,3,1518.5,t +2020,Alder,3,1685.8,t +2019,Dunlin,3,1888.1,t +2018,Birch,3,541000,kg +2018,Alder,2,1627.0,t +2023,Dunlin,1,1328.2,t +2018,Birch,2,772.4,t +2022,Birch,2,532.7,t +2020,Alder,2,1637800,kg +2018,Alder,1,2080.5,t +2021,Alder,1,1899.5,t +2021,Birch,2,586.5,t +2022,Dunlin,3,2073.1,t +2019,Birch,1,2482.8,t +2023,Alder,2,1310.4,t +2018,Dunlin,1,1433.3,t +2019,Alder,2,1560.9,t +2020,Birch,3,544300,kg +2023,Dunlin,2,2669.3,t +2024,Dunlin,3,1694.6,t +2024,Alder,3,1191.8,t +2021,Dunlin,1,1341.2,t +2024,Dunlin,2,2683.3,t +2019,Birch,3,549100,kg +2019,Alder,3,1773.4,t +2022,Alder,1,1917.3,t +2024,Dunlin,1,1278.6,t +2022,Dunlin,1,1296.9,t +2020,Birch,2,646.0,t +2021,Birch,1,2619.1,t +2019,Birch,2,703.7,t +2022,Dunlin,2,2568.2,t +2019,Dunlin,1,1468.6,t +2020,Dunlin,1,1435.3,t +2023,Alder,3,1338700,kg +2024,Alder,1,1841100,kg +2024,Alder,2,1244.7,t +2020,Alder,1,2027.5,t +2020,Birch,1,2578.4,t +2020,Dunlin,3,1965400,kg +2018,Dunlin,2,2709100,kg +2021,Dunlin,3,1956700,kg +2019,Dunlin,2,2715.1,t +2023,Dunlin,3,1869.1,t +2023,Alder,1,2008900,kg +2018,Alder,3,1837300,kg diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..541fda85ef42c333237b28711e034c6e68f051c7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/output.csv @@ -0,0 +1,20 @@ +year,site,output +2018,Dunlin,3290 +2020,Birch,5278 +2020,Alder,5607 +2023,Dunlin,3243 +2019,Dunlin,3210 +2019,Alder,5318 +2023,Alder,5558 +2022,Dunlin,3229 +2018,Birch,5285 +2018,Alder,5130 +2020,Dunlin,3344 +2024,Alder,5731 +2021,Alder,5385 +2019,Birch,5474 +2021,Birch,5079 +2022,Alder,5265 +2021,Dunlin,3178 +2024,Dunlin,3098 +2022,Birch,5384 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..238c2f678faadbca666cdec113a9ec346e0f1435 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Harlow Fold Logistics + +- Base year: 2018 +- Target year: 2029 +- Target: total emissions (scopes 1 to 3) 30 % below the base-year total. +- Output measure: thousand parcels delivered. +- Divested site: Birch (sold in 2023) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff6e0be3a7bad75149fc0a2d7ef4c9bf134e035c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (thousand parcels delivered); a year's output is the sum over sites. Site Birch was sold in 2023. Under the base-year recalculation policy in `target.md`, leave site Birch out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Harlow Fold Logistics (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2018"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2018. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2018. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2024 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2024, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2024 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2024 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..da68ead01b95913ea71589ffa49d89f3762987fb --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 59 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..7d8cce290088680a0ec4c92a944301e24831566a --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 11645.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 1383.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 11324.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 1327.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -2.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -2.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 11340.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 1266.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": 0.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -2.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 10847.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 1266.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -4.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -6.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 10620.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 1250.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": -2.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -8.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.total_t_co2e", + "type": "number", + "value": 10524.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.intensity_kg_per_unit", + "type": "number", + "value": 1195.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_previous_percent", + "type": "number", + "value": -0.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2023.change_vs_base_percent", + "type": "number", + "value": -9.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2024.total_t_co2e", + "type": "number", + "value": 9934.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2024.intensity_kg_per_unit", + "type": "number", + "value": 1125.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2024.change_vs_previous_percent", + "type": "number", + "value": -5.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2024.change_vs_base_percent", + "type": "number", + "value": -14.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 8151.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 356.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 9739.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 3.88, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0059/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..2a188fb8f5ffed61b56ec01f5a7b2aada6b815e3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/emissions_ledger.csv @@ -0,0 +1,79 @@ +year,site,scope,amount,unit +2017,Birch,2,1246900,kg +2018,Cedar,2,784.0,t +2016,Dunlin,1,158.8,t +2020,Elm,3,2167.0,t +2020,Dunlin,1,119500,kg +2017,Birch,1,214.7,t +2017,Cedar,1,928.8,t +2022,Elm,1,893600,kg +2019,Cedar,2,769500,kg +2018,Elm,3,2304100,kg +2022,Cedar,3,1627400,kg +2018,Cedar,3,1884.1,t +2016,Elm,2,2047200,kg +2022,Cedar,2,746.8,t +2022,Cedar,1,752.1,t +2018,Birch,3,1987.4,t +2022,Elm,2,1665.2,t +2019,Cedar,1,799700,kg +2019,Dunlin,2,1248.2,t +2019,Elm,1,852.3,t +2018,Birch,2,1148.7,t +2017,Dunlin,3,1152.9,t +2020,Birch,3,2123.3,t +2016,Dunlin,2,1212200,kg +2019,Cedar,3,1734.4,t +2017,Birch,3,2130.9,t +2021,Birch,3,1896.7,t +2020,Dunlin,3,1128.0,t +2020,Cedar,1,766.4,t +2019,Dunlin,1,128.1,t +2022,Elm,3,2123.3,t +2018,Cedar,1,870.5,t +2016,Birch,1,211.1,t +2017,Dunlin,2,1127.2,t +2016,Cedar,3,1750400,kg +2018,Dunlin,1,132500,kg +2021,Elm,1,851.2,t +2022,Birch,2,1091800,kg +2021,Elm,2,1696.4,t +2020,Birch,2,1214.1,t +2019,Birch,3,2063900,kg +2021,Birch,2,1112.2,t +2020,Birch,1,205.0,t +2019,Elm,3,2378000,kg +2019,Elm,2,1918400,kg +2017,Elm,2,2016.2,t +2020,Cedar,3,1568.7,t +2018,Birch,1,227500,kg +2016,Cedar,1,884100,kg +2018,Dunlin,3,1112600,kg +2018,Dunlin,2,1182500,kg +2018,Elm,1,949.3,t +2016,Elm,3,2343.2,t +2021,Cedar,2,752.8,t +2021,Elm,3,2008.1,t +2022,Birch,1,188.3,t +2019,Birch,2,1152.8,t +2016,Birch,3,2293800,kg +2021,Cedar,3,1540100,kg +2021,Birch,1,187.4,t +2016,Elm,1,1095500,kg +2016,Birch,2,1371.7,t +2020,Elm,2,1807.9,t +2019,Dunlin,3,1137.5,t +2016,Cedar,2,892.8,t +2016,Dunlin,3,1168200,kg +2019,Birch,1,204.1,t +2021,Cedar,1,762.3,t +2017,Cedar,3,1798.0,t +2017,Cedar,2,827.6,t +2017,Elm,1,1058300,kg +2017,Elm,3,2317500,kg +2022,Birch,3,1722800,kg +2020,Cedar,2,727.5,t +2020,Dunlin,2,1318.8,t +2017,Dunlin,1,143300,kg +2018,Elm,2,2057200,kg +2020,Elm,1,803.9,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..1dcda9daf6ed02eca05368956f4a428ba9bbecb8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/output.csv @@ -0,0 +1,27 @@ +year,site,output +2019,Elm,54518 +2017,Dunlin,26157 +2022,Cedar,22720 +2020,Dunlin,28593 +2020,Elm,54408 +2016,Dunlin,25995 +2019,Birch,72513 +2016,Cedar,24244 +2021,Elm,56968 +2017,Elm,53278 +2022,Elm,58399 +2021,Cedar,23820 +2020,Birch,75623 +2016,Birch,69542 +2022,Birch,79908 +2021,Birch,77866 +2018,Birch,72852 +2019,Cedar,25104 +2016,Elm,54237 +2020,Cedar,23928 +2018,Cedar,25810 +2019,Dunlin,27516 +2018,Elm,53258 +2017,Birch,69573 +2018,Dunlin,26013 +2017,Cedar,24775 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..95ac028bfdd4466d0da95ff92abcc100f158cfc8 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Vessby Dairy Cooperative + +- Base year: 2016 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 42 % below the base-year total. +- Output measure: m2 of heated floor area. +- Divested site: Dunlin (sold in 2021) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..640dee8c888083df86885c699550a7400c769d05 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (m2 of heated floor area); a year's output is the sum over sites. Site Dunlin was sold in 2021. Under the base-year recalculation policy in `target.md`, leave site Dunlin out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Vessby Dairy Cooperative (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2016"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2016. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2016. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2022 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2022, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2022 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2022 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a6747f002a3456d56d67eaf5567509f91afcddd7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 71 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..40f6a27e354f7a91c3e26af190826680dd82e60c --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 12889.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 87.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 12538.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 84.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -2.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -2.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 12212.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 80.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -2.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 11873.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 78.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -2.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -7.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 11383.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 73.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -4.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -11.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 10807.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 68.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -5.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -16.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.total_t_co2e", + "type": "number", + "value": 10811.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.intensity_kg_per_unit", + "type": "number", + "value": 67.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_previous_percent", + "type": "number", + "value": 0.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2022.change_vs_base_percent", + "type": "number", + "value": -16.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 7476.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 555.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 10182.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 5.96, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0071/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main() diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/Dockerfile b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/emissions_ledger.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/emissions_ledger.csv new file mode 100644 index 0000000000000000000000000000000000000000..3b8ae3df57737bdbf758b0d028d96815b089c4bc --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/emissions_ledger.csv @@ -0,0 +1,79 @@ +year,site,scope,amount,unit +2021,Dunlin,1,1510900,kg +2018,Elm,1,124.5,t +2015,Dunlin,3,2081700,kg +2017,Elm,1,135300,kg +2016,Elm,1,150.6,t +2016,Cedar,3,1257300,kg +2021,Cedar,3,1030.5,t +2015,Elm,3,1188.8,t +2018,Cedar,1,1592.5,t +2019,Cedar,3,1034.2,t +2019,Birch,3,215900,kg +2018,Birch,1,1546.6,t +2017,Dunlin,3,1978000,kg +2016,Birch,3,225200,kg +2018,Dunlin,2,1497000,kg +2021,Birch,1,1348900,kg +2017,Birch,3,230.4,t +2019,Birch,1,1562.7,t +2018,Birch,2,520.3,t +2016,Elm,3,1190.1,t +2016,Birch,1,1571.0,t +2020,Dunlin,3,1607.8,t +2015,Cedar,1,1545.7,t +2021,Birch,3,198.5,t +2021,Dunlin,2,1316.2,t +2017,Birch,2,531.0,t +2017,Elm,2,978.1,t +2020,Birch,1,1483.0,t +2019,Birch,2,548600,kg +2018,Dunlin,1,1730.2,t +2015,Dunlin,1,1685.7,t +2015,Elm,2,1022.8,t +2015,Cedar,3,1355.0,t +2021,Birch,2,491900,kg +2016,Dunlin,2,1764.0,t +2017,Elm,3,1124200,kg +2021,Cedar,2,1724.4,t +2018,Birch,3,212.7,t +2018,Cedar,3,1088.5,t +2016,Cedar,2,1873.4,t +2020,Dunlin,2,1471900,kg +2015,Birch,2,577.2,t +2019,Dunlin,2,1394.0,t +2020,Birch,3,208.7,t +2020,Cedar,2,1760.2,t +2015,Birch,3,229.1,t +2020,Dunlin,1,1553.4,t +2016,Birch,2,560900,kg +2015,Cedar,2,1910.9,t +2019,Dunlin,1,1744800,kg +2016,Dunlin,1,1584900,kg +2018,Dunlin,3,1953.6,t +2017,Dunlin,1,1669.5,t +2019,Elm,2,980.9,t +2015,Birch,1,1536.4,t +2019,Elm,1,117.5,t +2017,Birch,1,1578800,kg +2018,Cedar,2,1959.9,t +2018,Elm,3,1073.0,t +2017,Cedar,3,1209.2,t +2019,Elm,3,1125.3,t +2016,Dunlin,3,2092.0,t +2015,Elm,1,142.5,t +2017,Dunlin,2,1632.5,t +2016,Elm,2,1081.2,t +2019,Dunlin,3,1798.6,t +2017,Cedar,1,1507.9,t +2021,Cedar,1,1396200,kg +2020,Cedar,1,1554400,kg +2020,Birch,2,548.9,t +2020,Cedar,3,1083.5,t +2018,Elm,2,993.1,t +2017,Cedar,2,1919.2,t +2015,Dunlin,2,1917900,kg +2019,Cedar,1,1673500,kg +2021,Dunlin,3,1672700,kg +2016,Cedar,1,1439900,kg +2019,Cedar,2,1923.1,t diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/output.csv b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..65fd1b951ef2ab65c7c583af289129f7e6795fe5 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/output.csv @@ -0,0 +1,27 @@ +year,site,output +2020,Cedar,4881 +2017,Birch,3380 +2019,Dunlin,3258 +2015,Dunlin,3242 +2015,Birch,3560 +2017,Dunlin,3223 +2021,Dunlin,3211 +2016,Elm,4303 +2017,Cedar,4288 +2015,Elm,4170 +2017,Elm,4546 +2019,Elm,4317 +2018,Elm,4488 +2015,Cedar,4467 +2016,Birch,3473 +2021,Cedar,4908 +2018,Birch,3333 +2018,Dunlin,3250 +2020,Dunlin,3286 +2019,Cedar,4635 +2019,Birch,3504 +2020,Birch,3636 +2016,Cedar,4346 +2018,Cedar,4558 +2016,Dunlin,3240 +2021,Birch,3819 diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/target.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/target.md new file mode 100644 index 0000000000000000000000000000000000000000..37ba8440425c204a7cd78d6fccd2a492a774bb76 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/environment/workdir/target.md @@ -0,0 +1,8 @@ +# Emissions target: Brantholm Municipality + +- Base year: 2015 +- Target year: 2028 +- Target: total emissions (scopes 1 to 3) 42 % below the base-year total. +- Output measure: thousand parcels delivered. +- Divested site: Elm (sold in 2020) +- Base-year recalculation policy: when a site is sold, its emissions and output are removed from every year of the series, the base year included, so that all years cover the same sites. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/instruction.md b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14ca1b731c198f1b9ae3fa41b4eb39327df9e5f3 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/instruction.md @@ -0,0 +1,18 @@ +# Emissions inventory: trend and target + +`emissions_ledger.csv` holds one row per year, site and scope. The `amount` is in tonnes CO2e when `unit` is `t` and in kg CO2e when it is `kg` (1 tonne = 1000 kg). A year's total is the sum over all sites and scopes. `output.csv` gives each site's output per year (thousand parcels delivered); a year's output is the sum over sites. Site Elm was sold in 2020. Under the base-year recalculation policy in `target.md`, leave site Elm out of every year, in both emissions and output. `target.md` gives the base year and the reduction target of Brantholm Municipality (a synthetic organisation). + +Write `answer.json` in this folder, a JSON object with: + +- `years`: an object keyed by year (as a string, for example "2015"), each with + - `total_t_co2e`: scopes 1 to 3 together, tonnes CO2e, 1 decimal. + - `intensity_kg_per_unit`: kg CO2e per unit of output (total x 1000 / output), 1 decimal. + - `change_vs_previous_percent`: change in the total against the year before, in percent, 1 decimal (negative for a fall). Leave it out for 2015. + - `change_vs_base_percent`: change in the total against the base year, in percent, 1 decimal (negative for a fall). Leave it out for 2015. +- `target_t_co2e`: the total allowed in the target year, tonnes CO2e, 1 decimal. +- `required_annual_reduction_t`: the equal cut in tonnes CO2e per year that takes the 2021 total to the target by the target year: (latest total - target) / years left, 1 decimal. +- `linear_path_latest_t`: where a straight line from the base-year total (in the base year) to the target (in the target year) stands in 2021, tonnes CO2e, 1 decimal. +- `on_track`: true if the 2021 total is at or below `linear_path_latest_t`, otherwise false. +- `required_annual_reduction_percent`: the constant percentage cut per year that takes the 2021 total to the target by the target year, 2 decimals: (1 - (target / latest total)^(1 / years left)) x 100. + +A percentage change is (new - old) / old x 100. Do not round intermediate values. Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/solution/oracle.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..27a2b307ddbf11ae43e3012bbf778a030565cdcd --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/solution/oracle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Reference solution for Emissions Inventory. Works only from the files in the current directory.""" +import csv, json, os, re + +def rows(name): + with open(name, newline="") as f: return list(csv.DictReader(f)) + +def text(name): + with open(name) as f: return f.read() + +def activity(): + year = re.search(r"Reporting year:\s*(\d{4})", text("inventory_boundary.md")).group(1) + factors = dict((r["source"], r) for r in rows("emission_factors.csv")) + conv = rows("unit_conversions.csv") + recs = rows("activity_data.csv") + by_source, by_scope, by_site, outside = {}, {"scope_1": 0.0, "scope_2": 0.0, "scope_3": 0.0}, {}, 0.0 + for r in recs: + if r["invoice_date"][:4] != year: continue + f = factors[r["source"]] + q = float(r["quantity"]) + if r["unit"] != f["unit"]: + 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(";"))] + assert len(hit) == 1, (r, hit) + q *= float(hit[0]["multiply_by"]) + e = q * float(f["factor_kg_co2e_per_unit"]) / 1000.0 + by_source[r["source"]] = by_source.get(r["source"], 0.0) + e + if f["scope"] in ("1", "2", "3"): + by_scope["scope_" + f["scope"]] += e + by_site[r["site"]] = by_site.get(r["site"], 0.0) + e + else: outside += e + total = sum(by_scope.values()) + in_scope = [s for s in by_source if factors[s]["scope"] in ("1", "2", "3")] + r2 = lambda d_: dict((k, round(v, 2)) for k, v in d_.items()) + 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), + "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])} + +def multigas(): + gwp = {} + for line in text("gwp_values.md").splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if line.strip().startswith("|") and len(cells) == 2 and re.match(r"^[0-9.]+$", cells[1]): gwp[cells[0]] = float(cells[1]) + factors = dict((r["category"], r) for r in rows("gas_factors.csv")) + to_unit = {("m3", "litre"): 1000.0, ("kg", "tonne"): 0.001} + ans = {"sources": {}} + tot = {"co2_t": 0.0, "ch4_t_co2e": 0.0, "n2o_t_co2e": 0.0} + full = {} + for r in rows("sources.csv"): + f = factors[r["category"]] + amount = float(r["amount"]) * (1.0 if r["unit"] == f["unit"] else to_unit[(r["unit"], f["unit"])]) + co2 = amount * float(f["co2_kg_per_unit"]) / 1000.0 + ch4 = amount * float(f["ch4_g_per_unit"]) / 1000.0 + n2o = amount * float(f["n2o_g_per_unit"]) / 1000.0 + e = co2 * gwp["CO2"] + ch4 * gwp["CH4"] / 1000.0 + n2o * gwp["N2O"] / 1000.0 + 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)} + full[r["source_id"]] = e + tot["co2_t"] += co2; tot["ch4_t_co2e"] += ch4 * gwp["CH4"] / 1000.0; tot["n2o_t_co2e"] += n2o * gwp["N2O"] / 1000.0 + hfc = 0.0 + if os.path.exists("refrigerant_log.csv"): + for r in rows("refrigerant_log.csv"): hfc += float(r["topped_up_kg"]) * gwp[r["refrigerant"]] / 1000.0 + grand = sum(tot.values()) + hfc + ans["totals"] = dict((k, round(v, 2)) for k, v in tot.items()) + ans["totals"]["co2e_t"] = round(grand, 2) + 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])) + return ans + +def series(): + target = text("target.md") + base = int(re.search(r"Base year:\s*(\d{4})", target).group(1)) + target_year = int(re.search(r"Target year:\s*(\d{4})", target).group(1)) + cut = float(re.search(r"([0-9.]+)\s*% below", target).group(1)) + totals, output = {}, {} + if os.path.exists("annual_emissions.csv"): + for r in rows("annual_emissions.csv"): + totals[int(r["year"])] = float(r["scope_1_t"]) + float(r["scope_2_t"]) + float(r["scope_3_t"]) + output[int(r["year"])] = float(r["output"]) + else: + ledger, out = rows("emissions_ledger.csv"), rows("output.csv") + sold = re.search(r"Divested site:\s*(\w+)", target) + still = set(r["site"] for r in ledger) - set([sold.group(1)] if sold else []) + for r in ledger: + if r["site"] not in still: continue + y = int(r["year"]) + totals[y] = totals.get(y, 0.0) + float(r["amount"]) / (1000.0 if r["unit"] == "kg" else 1.0) + for r in out: + if "site" in r and r["site"] not in still: continue + output[int(r["year"])] = output.get(int(r["year"]), 0.0) + float(r["output"]) + years = sorted(totals) + latest = years[-1] + ans = {"years": {}} + for i, y in enumerate(years): + o = {"total_t_co2e": round(totals[y], 1), "intensity_kg_per_unit": round(totals[y] * 1000.0 / output[y], 1)} + if y != base: + o["change_vs_previous_percent"] = round((totals[y] - totals[years[i - 1]]) / totals[years[i - 1]] * 100, 1) + o["change_vs_base_percent"] = round((totals[y] - totals[base]) / totals[base] * 100, 1) + ans["years"][str(y)] = o + goal = totals[base] * (1 - cut / 100.0) + left = target_year - latest + path = totals[base] - (totals[base] - goal) * (latest - base) / float(target_year - base) + 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), + on_track=totals[latest] <= path, required_annual_reduction_percent=round((1 - (goal / totals[latest]) ** (1.0 / left)) * 100, 2)) + return ans + +def quality(): + factor = float(re.search(r"emission factor:\s*([0-9.]+)", text("data_rules.md")).group(1)) + seen, dups, site = {}, {}, {} + for r in rows("meter_readings.csv"): + m = r["meter_id"] + site[m] = r["site"]; seen.setdefault(m, {}); dups.setdefault(m, 0) + kwh = float(r["consumption"]) * (1000.0 if r["unit"] == "MWh" else 1.0) + if r["month"] in seen[m]: + assert abs(seen[m][r["month"]] - kwh) < 1e-6 + dups[m] += 1 + else: seen[m][r["month"]] = kwh + year = sorted(next(iter(seen.values())))[0][:4] + months = ["%s-%02d" % (year, k) for k in range(1, 13)] + ans = {"meters": {}, "filled": {}, "meters_with_gap": []} + month_total, site_total, total = dict((mo, 0.0) for mo in months), {}, 0.0 + for m, have in seen.items(): + filled = {} + for i, mo in enumerate(months): + if mo not in have: filled[mo] = (have[months[i - 1]] + have[months[i + 1]]) / 2.0 + if filled: + ans["filled"][m] = dict((mo, round(v, 1)) for mo, v in filled.items()); ans["meters_with_gap"].append(m) + have = dict(have); have.update(filled) + annual = sum(have.values()) + ans["meters"][m] = {"annual_kwh": round(annual, 1), "duplicate_rows": dups[m]} + for mo in months: month_total[mo] += have[mo] + site_total[site[m]] = site_total.get(site[m], 0.0) + annual + total += annual + ans.update(duplicate_rows_removed=sum(dups.values()), total_kwh=round(total, 1), total_t_co2e=round(total * factor / 1000.0, 2), + 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])) + return ans + +if os.path.exists("activity_data.csv"): answer = activity() +elif os.path.exists("gwp_values.md"): answer = multigas() +elif os.path.exists("target.md"): answer = series() +else: answer = quality() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/solution/solve.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/task.toml b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f98885f02a7054facf4accc030bacac12c1b46e7 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "emissions-inventory" +tags = ["emissions-inventory", "time-series", "isced-0521", "train"] +isced_f = "0521" +family = "time-series" +split = "train" +seed = 83 + +[verifier] +timeout_sec = 120.0 + +[agent] +timeout_sec = 900.0 + +[environment] +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 +allow_internet = false diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/checks.json b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..030da17e36fef73ae7209a835620bd17c180b41e --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/checks.json @@ -0,0 +1,218 @@ +[ + { + "path": "years.2015.total_t_co2e", + "type": "number", + "value": 12839.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2015.intensity_kg_per_unit", + "type": "number", + "value": 1139.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.total_t_co2e", + "type": "number", + "value": 12368.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.intensity_kg_per_unit", + "type": "number", + "value": 1118.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.change_vs_previous_percent", + "type": "number", + "value": -3.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2016.change_vs_base_percent", + "type": "number", + "value": -3.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.total_t_co2e", + "type": "number", + "value": 12256.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.intensity_kg_per_unit", + "type": "number", + "value": 1125.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_previous_percent", + "type": "number", + "value": -0.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2017.change_vs_base_percent", + "type": "number", + "value": -4.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.total_t_co2e", + "type": "number", + "value": 12101.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.intensity_kg_per_unit", + "type": "number", + "value": 1086.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_previous_percent", + "type": "number", + "value": -1.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2018.change_vs_base_percent", + "type": "number", + "value": -5.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.total_t_co2e", + "type": "number", + "value": 11895.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.intensity_kg_per_unit", + "type": "number", + "value": 1043.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_previous_percent", + "type": "number", + "value": -1.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2019.change_vs_base_percent", + "type": "number", + "value": -7.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.total_t_co2e", + "type": "number", + "value": 11271.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.intensity_kg_per_unit", + "type": "number", + "value": 955.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_previous_percent", + "type": "number", + "value": -5.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2020.change_vs_base_percent", + "type": "number", + "value": -12.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.total_t_co2e", + "type": "number", + "value": 10690.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.intensity_kg_per_unit", + "type": "number", + "value": 895.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_previous_percent", + "type": "number", + "value": -5.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "years.2021.change_vs_base_percent", + "type": "number", + "value": -16.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "target_t_co2e", + "type": "number", + "value": 7447.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_t", + "type": "number", + "value": 463.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "linear_path_latest_t", + "type": "number", + "value": 10350.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "on_track", + "type": "bool", + "value": false, + "weight": 1.0 + }, + { + "path": "required_annual_reduction_percent", + "type": "number", + "value": 5.03, + "abs_tol": 0.01, + "weight": 1.0 + } +] diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/test.sh b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/verify.py --answer /app/answer.json --checks /tests/checks.json --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/verify.py b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/emissions-inventory/emissions-inventory-time-series-d3-t0083/tests/verify.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Verifier for Renaissance Labs practice environments. Standard library only. + +Reads the agent's answer (a JSON object) and a list of checks, and writes a reward in [0, 1]. +The reward is the weighted share of checks that pass. A missing, unreadable or non-object +answer scores 0. Each check addresses one value in the answer by a dotted path. + +Check types + int exact integer (a float with integral value is accepted; booleans are not) + number within abs_tol of value (default 1e-9); booleans and strings are rejected + str equal after trimming and case-folding + bool exact boolean + list ordered list; items compared as int/number/str according to "item" (default str) + set unordered collection of distinct strings (or ints) + custom a function in validators.py: name(answer, args) -> bool or float in [0, 1] +""" +import argparse, json, math, os, sys + +MISSING = object() + +def lookup(obj, path): + cur = obj + for part in path.split("."): + if isinstance(cur, dict): + if part not in cur: return MISSING + cur = cur[part] + elif isinstance(cur, list): + try: cur = cur[int(part)] + except (ValueError, IndexError): return MISSING + else: + return MISSING + return cur + +def is_num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) and not (isinstance(x, float) and (math.isnan(x) or math.isinf(x))) + +def eq_int(got, want): + return is_num(got) and float(got) == float(int(got)) and int(got) == want + +def eq_num(got, want, tol): + return is_num(got) and abs(float(got) - float(want)) <= tol + 1e-12 + +def eq_str(got, want): + return isinstance(got, str) and got.strip().casefold() == str(want).strip().casefold() + +def eq_item(got, want, kind, tol): + if kind == "int": return eq_int(got, want) + if kind == "number": return eq_num(got, want, tol) + return eq_str(got, want) + +def run_check(answer, chk, validators): + t = chk["type"] + if t == "custom": + fn = getattr(validators, chk["name"], None) if validators else None + if fn is None: return 0.0 + try: r = fn(answer, chk.get("args", {})) + except Exception: return 0.0 + if r is True: return 1.0 + if r is False or r is None: return 0.0 + return max(0.0, min(1.0, float(r))) if is_num(r) else 0.0 + got = lookup(answer, chk["path"]) + if got is MISSING: return 0.0 + want, tol = chk["value"], chk.get("abs_tol", 1e-9) + if t == "int": ok = eq_int(got, want) + elif t == "number": ok = eq_num(got, want, tol) + elif t == "str": ok = eq_str(got, want) + elif t == "bool": ok = isinstance(got, bool) and got is want + elif t == "list": + ok = isinstance(got, list) and len(got) == len(want) and all(eq_item(g, w, chk.get("item", "str"), tol) for g, w in zip(got, want)) + elif t == "set": + kind = chk.get("item", "str") + if not isinstance(got, list): ok = False + else: + norm = (lambda x: x.strip().casefold() if isinstance(x, str) else None) if kind == "str" else (lambda x: int(x) if eq_int(x, int(x) if is_num(x) else 0) else None) + g = [norm(x) for x in got]; w = [norm(x) for x in want] + ok = None not in g and len(g) == len(set(g)) and set(g) == set(w) + else: ok = False + return 1.0 if ok else 0.0 + +def grade(answer, checks, validators=None): + """Return (reward, details). answer is the parsed JSON, or None if it could not be read.""" + if not isinstance(answer, dict): + return 0.0, [{"check": c.get("path", c.get("name")), "score": 0.0} for c in checks] + total = sum(c.get("weight", 1.0) for c in checks) + got, details = 0.0, [] + for c in checks: + s = run_check(answer, c, validators) + got += s * c.get("weight", 1.0) + details.append({"check": c.get("path", c.get("name")), "score": s}) + return (round(got / total, 6) if total else 0.0), details + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--answer", default="/app/answer.json") + ap.add_argument("--checks", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "checks.json")) + ap.add_argument("--out", default="/logs/verifier") + a = ap.parse_args() + checks = json.load(open(a.checks)) + try: + with open(a.answer) as f: answer = json.load(f) + except Exception: + answer = None + validators = None + here = os.path.dirname(os.path.abspath(__file__)) + if os.path.exists(os.path.join(here, "validators.py")): + sys.path.insert(0, here) + import validators # noqa + reward, details = grade(answer, checks, validators) + os.makedirs(a.out, exist_ok=True) + with open(os.path.join(a.out, "reward.txt"), "w") as f: f.write(str(reward)) + with open(os.path.join(a.out, "reward.json"), "w") as f: + json.dump({"reward": reward, "solved": reward == 1.0, "passed": sum(1 for d in details if d["score"] == 1.0), "checks": len(details)}, f) + print("reward", reward) + +if __name__ == "__main__": + main()