diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..b7fe822c5b9825b45ee77ea41025004622945feb --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C116,F,37,22,occupational health +C337,F,25,28,self +C286,M,33,37,GP +C228,F,72,25,self +C324,M,39,28,self +C319,F,40,27,self diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..cfcf7e499d31134913449e267a22b589489cd659 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,45-59,M,681,18.9,6.0 +IRR,Irritability Scale,18-29,M,267,23.7,7.8 +IRR,Irritability Scale,30-44,M,651,24.8,8.1 +IRR,Irritability Scale,45-59,F,239,23.7,7.0 +IRR,Irritability Scale,18-29,F,484,22.5,5.9 +IRR,Irritability Scale,30-44,F,857,25.2,5.4 +IRR,Irritability Scale,60-74,M,814,24.1,7.6 +IRR,Irritability Scale,60-74,F,504,22.6,8.1 diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-e0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36ca38fb64d7c220d8c367b513b08e8e5842feb7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-e0000/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-e0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/task.toml b/tasks/psychometrics/psychometrics-norms-d1-e0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd9ad691d31841bac4d97568eee3131903de9d8f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "eval"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-e0000/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-e0000/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c762fc40b5117490f363a9be36eba4f95c4f6d73 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0000/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C228.z", + "type": "number", + "value": 0.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C228.t_score", + "type": "number", + "value": 53.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C228.percentile", + "type": "number", + "value": 61.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C337.z", + "type": "number", + "value": 0.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C337.t_score", + "type": "number", + "value": 59.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C337.percentile", + "type": "number", + "value": 82.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C116.z", + "type": "number", + "value": -0.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C116.t_score", + "type": "number", + "value": 44.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C116.percentile", + "type": "number", + "value": 27.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C286.z", + "type": "number", + "value": 1.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C286.t_score", + "type": "number", + "value": 65.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C286.percentile", + "type": "number", + "value": 93.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C324.z", + "type": "number", + "value": 0.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C324.t_score", + "type": "number", + "value": 54.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C324.percentile", + "type": "number", + "value": 65.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C319.z", + "type": "number", + "value": 0.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C319.t_score", + "type": "number", + "value": 53.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C319.percentile", + "type": "number", + "value": 63.1, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0000/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-e0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-e0000/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-e0000/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-e0012/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..05a11f18f569edbe142cd928d8b3031cc3c5cd3c --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C235,F,31,29,self +C267,M,56,37,self +C216,M,50,41,GP +C330,F,44,24,occupational health +C168,M,51,14,GP +C217,M,65,23,GP diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..8986a1094dbc176d66ba15b48f92f410db1243eb --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,45-59,M,828,25.2,7.8 +IRR,Irritability Scale,45-59,F,287,27.1,5.7 +IRR,Irritability Scale,60-74,F,612,30.2,6.8 +IRR,Irritability Scale,60-74,M,246,31.6,7.3 +IRR,Irritability Scale,18-29,M,670,26.4,8.1 +IRR,Irritability Scale,30-44,F,664,26.0,4.4 +IRR,Irritability Scale,30-44,M,295,26.1,4.4 +IRR,Irritability Scale,18-29,F,652,27.0,4.4 diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0012/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-e0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36ca38fb64d7c220d8c367b513b08e8e5842feb7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0012/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-e0012/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0012/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-e0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0012/task.toml b/tasks/psychometrics/psychometrics-norms-d1-e0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..df41abf90e8708c9caac0f3491e51259427aa163 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "eval"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-e0012/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-e0012/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..bba33204574b6919f18aefbb1b1a2a2c650a6899 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-e0012/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C216.z", + "type": "number", + "value": 2.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C216.t_score", + "type": "number", + "value": 70.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C216.percentile", + "type": "number", + "value": 97.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C168.z", + "type": "number", + "value": -1.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C168.t_score", + "type": "number", + "value": 35.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C168.percentile", + "type": "number", + "value": 7.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C267.z", + "type": "number", + "value": 1.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C267.t_score", + "type": "number", + "value": 65.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C267.percentile", + "type": "number", + "value": 93.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C330.z", + "type": "number", + "value": -0.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C330.t_score", + "type": "number", + "value": 45.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C330.percentile", + "type": "number", + "value": 32.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C217.z", + "type": "number", + "value": -1.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C217.t_score", + "type": "number", + "value": 38.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C217.percentile", + "type": "number", + "value": 11.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C235.z", + "type": "number", + "value": 0.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C235.t_score", + "type": "number", + "value": 56.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C235.percentile", + "type": "number", + "value": 75.2, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-e0012/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-e0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-e0012/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-e0012/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0000/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..37ff2cee8bb284949de545d3a43df658315ccbbd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C134,M,48,19,GP +C117,M,70,30,self +C341,F,32,34,occupational health +C195,F,69,24,occupational health +C129,M,32,24,GP +C283,M,48,29,self diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..53ed4c15270f6dcff91aedfbae26b89ed9915633 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,18-29,M,235,20.7,8.4 +IRR,Irritability Scale,30-44,F,126,18.8,8.0 +IRR,Irritability Scale,18-29,F,503,22.9,6.7 +IRR,Irritability Scale,60-74,M,270,21.5,7.3 +IRR,Irritability Scale,45-59,M,775,21.6,4.4 +IRR,Irritability Scale,45-59,F,194,17.6,6.3 +IRR,Irritability Scale,60-74,F,617,21.5,4.5 +IRR,Irritability Scale,30-44,M,401,17.8,8.1 diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0000/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36ca38fb64d7c220d8c367b513b08e8e5842feb7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0000/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-t0000/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0000/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-t0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0000/task.toml b/tasks/psychometrics/psychometrics-norms-d1-t0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..24a60c1fc0b25e9b8f4ffb5fdabd2eb913abdec0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-t0000/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-t0000/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..208c38a9cae46b79025713efcd625d2fab064b94 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0000/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C129.z", + "type": "number", + "value": 0.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C129.t_score", + "type": "number", + "value": 57.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C129.percentile", + "type": "number", + "value": 77.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C195.z", + "type": "number", + "value": 0.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C195.t_score", + "type": "number", + "value": 55.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C195.percentile", + "type": "number", + "value": 71.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C134.z", + "type": "number", + "value": -0.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C134.t_score", + "type": "number", + "value": 44.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C134.percentile", + "type": "number", + "value": 27.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C283.z", + "type": "number", + "value": 1.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C283.t_score", + "type": "number", + "value": 66.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C283.percentile", + "type": "number", + "value": 95.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C341.z", + "type": "number", + "value": 1.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C341.t_score", + "type": "number", + "value": 69.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C341.percentile", + "type": "number", + "value": 97.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C117.z", + "type": "number", + "value": 1.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C117.t_score", + "type": "number", + "value": 61.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C117.percentile", + "type": "number", + "value": 87.8, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0000/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-t0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0000/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-t0000/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0012/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..fc6ef95cbc6209524de93d7690563eccd4338fcc --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C104,F,25,32,self +C232,F,65,28,self +C312,M,50,36,self +C292,M,52,15,GP +C207,M,49,38,self +C202,M,50,22,GP diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..3d28536472bcbd052731d8ff2bce45a4703dac09 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +ATT,Attention Difficulties Scale,18-29,M,296,19.7,6.6 +ATT,Attention Difficulties Scale,60-74,M,585,21.6,5.1 +ATT,Attention Difficulties Scale,30-44,F,786,19.2,7.8 +ATT,Attention Difficulties Scale,60-74,F,878,17.3,5.0 +ATT,Attention Difficulties Scale,18-29,F,671,21.2,5.1 +ATT,Attention Difficulties Scale,45-59,F,865,25.1,4.5 +ATT,Attention Difficulties Scale,45-59,M,584,23.8,6.7 +ATT,Attention Difficulties Scale,30-44,M,593,18.2,7.1 diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0012/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-t0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bcc97e760dddef22521f364e10dfe41531f22357 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Attention Difficulties Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0012/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-t0012/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0012/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-t0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0012/task.toml b/tasks/psychometrics/psychometrics-norms-d1-t0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b63f00add564ee494d3c99945662b4ef2fbaebc0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-t0012/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-t0012/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c820066bab8b67a13435e918eb65cdbfa1bd6c68 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0012/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C202.z", + "type": "number", + "value": -0.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C202.t_score", + "type": "number", + "value": 47.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C202.percentile", + "type": "number", + "value": 39.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C292.z", + "type": "number", + "value": -1.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C292.t_score", + "type": "number", + "value": 36.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C292.percentile", + "type": "number", + "value": 9.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C104.z", + "type": "number", + "value": 2.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C104.t_score", + "type": "number", + "value": 71.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C104.percentile", + "type": "number", + "value": 98.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C312.z", + "type": "number", + "value": 1.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C312.t_score", + "type": "number", + "value": 68.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C312.percentile", + "type": "number", + "value": 96.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C232.z", + "type": "number", + "value": 2.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C232.t_score", + "type": "number", + "value": 71.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C232.percentile", + "type": "number", + "value": 98.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C207.z", + "type": "number", + "value": 2.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C207.t_score", + "type": "number", + "value": 71.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C207.percentile", + "type": "number", + "value": 98.3, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0012/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-t0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0012/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-t0012/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0024/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..2cc00e5034b8237cd2e54d5aa6eb28539746a143 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C363,F,53,44,self +C102,M,38,28,self +C368,M,60,48,self +C259,M,48,40,GP +C246,F,52,26,GP +C238,F,53,35,self diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..4c5aaf4a0cb1a22c5f972e1bdc52cc2f1a3cee10 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,60-74,M,625,32.2,5.9 +FAT,Fatigue Scale,30-44,F,559,26.3,4.1 +FAT,Fatigue Scale,45-59,F,504,30.9,4.8 +FAT,Fatigue Scale,30-44,M,643,29.0,8.2 +FAT,Fatigue Scale,45-59,M,131,26.2,6.3 +FAT,Fatigue Scale,60-74,F,284,26.8,7.2 +FAT,Fatigue Scale,18-29,M,155,28.1,6.5 +FAT,Fatigue Scale,18-29,F,288,27.1,5.1 diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0024/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-t0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ffe206239f25bf023640bcca5d23d8ef642e856 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Fatigue Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0024/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-t0024/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0024/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-t0024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0024/task.toml b/tasks/psychometrics/psychometrics-norms-d1-t0024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..98295b9284868d190e2b76da44f12f872952c02a --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-t0024/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-t0024/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..19645c3d4c5c41124291ef255bc297bee549d630 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0024/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C363.z", + "type": "number", + "value": 2.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C363.t_score", + "type": "number", + "value": 77.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C363.percentile", + "type": "number", + "value": 99.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C259.z", + "type": "number", + "value": 2.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C259.t_score", + "type": "number", + "value": 71.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C259.percentile", + "type": "number", + "value": 98.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C238.z", + "type": "number", + "value": 0.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C238.t_score", + "type": "number", + "value": 58.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C238.percentile", + "type": "number", + "value": 80.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C102.z", + "type": "number", + "value": -0.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C102.t_score", + "type": "number", + "value": 48.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C102.percentile", + "type": "number", + "value": 45.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C368.z", + "type": "number", + "value": 2.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C368.t_score", + "type": "number", + "value": 76.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C368.percentile", + "type": "number", + "value": 99.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C246.z", + "type": "number", + "value": -1.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C246.t_score", + "type": "number", + "value": 39.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C246.percentile", + "type": "number", + "value": 15.4, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0024/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-t0024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0024/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-t0024/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0036/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..a9c2e35a69b1991da6dfcfb61fb3a489d53b1fd5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C396,M,23,32,GP +C107,M,25,39,occupational health +C342,M,46,22,GP +C241,M,22,30,occupational health +C199,F,48,34,GP +C293,F,73,32,GP diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..4c41cac9cdd799eb80b90bf9f5889a58706f3703 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,60-74,F,872,24.7,6.4 +FAT,Fatigue Scale,60-74,M,182,29.1,7.8 +FAT,Fatigue Scale,18-29,F,504,26.2,5.5 +FAT,Fatigue Scale,45-59,F,801,20.7,5.2 +FAT,Fatigue Scale,30-44,M,591,21.2,7.1 +FAT,Fatigue Scale,18-29,M,499,23.2,6.1 +FAT,Fatigue Scale,30-44,F,840,25.9,8.3 +FAT,Fatigue Scale,45-59,M,235,21.4,4.1 diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0036/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ffe206239f25bf023640bcca5d23d8ef642e856 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Fatigue Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0036/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-t0036/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0036/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-t0036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0036/task.toml b/tasks/psychometrics/psychometrics-norms-d1-t0036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f0d89f30a70d36c76883281e7e2207ba34d6ff7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-t0036/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-t0036/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b6ee234a1f9ef636e797394d7d5bef458a4c5178 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0036/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C293.z", + "type": "number", + "value": 1.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C293.t_score", + "type": "number", + "value": 61.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C293.percentile", + "type": "number", + "value": 87.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C396.z", + "type": "number", + "value": 1.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C396.t_score", + "type": "number", + "value": 64.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C396.percentile", + "type": "number", + "value": 92.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C241.z", + "type": "number", + "value": 1.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C241.t_score", + "type": "number", + "value": 61.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C241.percentile", + "type": "number", + "value": 86.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C199.z", + "type": "number", + "value": 2.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C199.t_score", + "type": "number", + "value": 75.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C199.percentile", + "type": "number", + "value": 99.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C107.z", + "type": "number", + "value": 2.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C107.t_score", + "type": "number", + "value": 75.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C107.percentile", + "type": "number", + "value": 99.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C342.z", + "type": "number", + "value": 0.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C342.t_score", + "type": "number", + "value": 51.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C342.percentile", + "type": "number", + "value": 55.8, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0036/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-t0036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0036/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-t0036/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0048/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..35cbb496ab7cdca0afb0818810acd9da7c440c56 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C154,M,39,14,self +C128,F,53,14,GP +C177,M,30,22,occupational health +C270,F,44,13,occupational health +C246,M,60,12,GP +C313,F,41,18,GP diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..b8897864bed1b2b874a0ce3c5be9fca7cf01d39d --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,60-74,F,286,23.0,5.9 +IRR,Irritability Scale,45-59,M,756,17.3,6.2 +IRR,Irritability Scale,45-59,F,852,21.0,4.6 +IRR,Irritability Scale,18-29,F,221,15.9,8.4 +IRR,Irritability Scale,18-29,M,856,15.1,8.5 +IRR,Irritability Scale,30-44,M,500,18.5,4.8 +IRR,Irritability Scale,60-74,M,505,18.1,7.8 +IRR,Irritability Scale,30-44,F,412,14.7,4.0 diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0048/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-t0048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36ca38fb64d7c220d8c367b513b08e8e5842feb7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0048/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-t0048/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0048/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-t0048/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0048/task.toml b/tasks/psychometrics/psychometrics-norms-d1-t0048/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..022420b2bce9b2b8d99cea81ff8801e606c1f9bc --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-t0048/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-t0048/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..58a6db519cbd0a1b5ec185dcd348e2bd7e4840db --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0048/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C128.z", + "type": "number", + "value": -1.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C128.t_score", + "type": "number", + "value": 34.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C128.percentile", + "type": "number", + "value": 6.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C154.z", + "type": "number", + "value": -0.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C154.t_score", + "type": "number", + "value": 40.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C154.percentile", + "type": "number", + "value": 17.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C177.z", + "type": "number", + "value": 0.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C177.t_score", + "type": "number", + "value": 57.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C177.percentile", + "type": "number", + "value": 76.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C246.z", + "type": "number", + "value": -0.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C246.t_score", + "type": "number", + "value": 42.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C246.percentile", + "type": "number", + "value": 21.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C313.z", + "type": "number", + "value": 0.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C313.t_score", + "type": "number", + "value": 58.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C313.percentile", + "type": "number", + "value": 79.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C270.z", + "type": "number", + "value": -0.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C270.t_score", + "type": "number", + "value": 45.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C270.percentile", + "type": "number", + "value": 33.5, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0048/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-t0048/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0048/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-t0048/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0060/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..7f36ae58ce249692710bb9560a262cecf46a4c30 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C254,F,51,12,occupational health +C257,F,39,13,occupational health +C147,F,26,16,GP +C314,F,72,14,self +C158,F,73,20,occupational health +C311,F,50,24,self diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..d01aa88d96df8101c579be1ea41bf30562cc9a3e --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,18-29,F,395,15.0,8.5 +FAT,Fatigue Scale,60-74,F,173,15.0,7.6 +FAT,Fatigue Scale,45-59,F,825,17.2,7.1 +FAT,Fatigue Scale,30-44,M,349,16.2,8.0 +FAT,Fatigue Scale,60-74,M,724,19.8,5.5 +FAT,Fatigue Scale,45-59,M,456,15.7,5.0 +FAT,Fatigue Scale,30-44,F,369,15.4,6.0 +FAT,Fatigue Scale,18-29,M,394,13.7,5.6 diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0060/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-t0060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ffe206239f25bf023640bcca5d23d8ef642e856 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Fatigue Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0060/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-t0060/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0060/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-t0060/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0060/task.toml b/tasks/psychometrics/psychometrics-norms-d1-t0060/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..af07afc0a8e6dbde03cf123314a3955527e3c9f6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-t0060/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-t0060/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..57b54aab27a4b911aa4ba94468be700bf2369c85 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0060/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C311.z", + "type": "number", + "value": 0.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C311.t_score", + "type": "number", + "value": 59.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C311.percentile", + "type": "number", + "value": 83.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C257.z", + "type": "number", + "value": -0.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C257.t_score", + "type": "number", + "value": 46.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C257.percentile", + "type": "number", + "value": 34.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C158.z", + "type": "number", + "value": 0.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C158.t_score", + "type": "number", + "value": 56.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C158.percentile", + "type": "number", + "value": 74.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C147.z", + "type": "number", + "value": 0.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C147.t_score", + "type": "number", + "value": 51.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C147.percentile", + "type": "number", + "value": 54.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C254.z", + "type": "number", + "value": -0.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C254.t_score", + "type": "number", + "value": 42.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C254.percentile", + "type": "number", + "value": 23.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C314.z", + "type": "number", + "value": -0.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C314.t_score", + "type": "number", + "value": 48.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C314.percentile", + "type": "number", + "value": 44.8, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0060/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-t0060/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0060/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-t0060/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0072/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..be4ab14611441469450109bda128464d5e8fd7b7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/clients.csv @@ -0,0 +1,7 @@ +client_id,sex,age,raw_score,referral +C192,F,62,27,GP +C250,M,58,32,GP +C166,F,50,29,occupational health +C335,F,33,21,GP +C283,F,44,29,self +C390,M,18,28,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..7cf416f3293e4c0866c577e05e67d25022df58a0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,60-74,F,349,23.0,5.3 +IRR,Irritability Scale,30-44,M,843,22.0,4.6 +IRR,Irritability Scale,45-59,M,202,17.0,6.3 +IRR,Irritability Scale,18-29,M,811,18.6,6.3 +IRR,Irritability Scale,45-59,F,304,21.2,7.2 +IRR,Irritability Scale,60-74,M,514,14.6,8.4 +IRR,Irritability Scale,18-29,F,650,20.4,4.8 +IRR,Irritability Scale,30-44,F,726,22.9,6.6 diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d768ab9fd3d32fd5b0948347f588ca7d59a24814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/environment/workdir/norms_guide.md @@ -0,0 +1,13 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0072/instruction.md b/tasks/psychometrics/psychometrics-norms-d1-t0072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36ca38fb64d7c220d8c367b513b08e8e5842feb7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/instruction.md @@ -0,0 +1,14 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0072/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d1-t0072/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0072/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d1-t0072/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0072/task.toml b/tasks/psychometrics/psychometrics-norms-d1-t0072/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6936bc1812398e4a8371d8296d3a52c7dc5956e9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d1-t0072/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d1-t0072/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e4355d41d884c806c887a5b570ec1420433361d8 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d1-t0072/tests/checks.json @@ -0,0 +1,128 @@ +[ + { + "path": "clients.C166.z", + "type": "number", + "value": 1.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C166.t_score", + "type": "number", + "value": 60.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C166.percentile", + "type": "number", + "value": 86.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C335.z", + "type": "number", + "value": -0.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C335.t_score", + "type": "number", + "value": 47.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C335.percentile", + "type": "number", + "value": 38.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C283.z", + "type": "number", + "value": 0.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C283.t_score", + "type": "number", + "value": 59.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C283.percentile", + "type": "number", + "value": 82.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C250.z", + "type": "number", + "value": 2.38, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C250.t_score", + "type": "number", + "value": 73.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C250.percentile", + "type": "number", + "value": 99.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C390.z", + "type": "number", + "value": 1.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C390.t_score", + "type": "number", + "value": 64.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C390.percentile", + "type": "number", + "value": 93.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C192.z", + "type": "number", + "value": 0.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C192.t_score", + "type": "number", + "value": 57.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C192.percentile", + "type": "number", + "value": 77.5, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d1-t0072/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d1-t0072/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d1-t0072/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d1-t0072/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-e0004/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..45f07872b748098b221c7530d545ba50c67a1eab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C245,M,1965-05-21,2025-09-23,28,self +C295,F,2008-02-03,2025-06-09,26,GP +C239,F,1948-08-06,2025-05-14,19,occupational health +C384,F,1967-01-12,2025-06-12,35,occupational health +C168,M,1970-03-13,2025-05-19,22,self +C138,M,1965-07-03,2025-06-28,33,self +C327,F,1952-06-01,2025-02-23,37,self +C203,F,1979-12-04,2025-10-05,9,GP diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..766a24c1321fa982ef3aed5390a8a768305b87d4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,60-74,F,188,25.7,8.0 +IRR,Irritability Scale,30-44,F,151,20.9,7.4 +IRR,Irritability Scale,45-59,M,688,21.1,6.1 +IRR,Irritability Scale,18-29,M,369,19.7,6.1 +IRR,Irritability Scale,30-44,M,122,19.5,5.7 +IRR,Irritability Scale,18-29,F,232,19.8,7.1 +IRR,Irritability Scale,45-59,F,445,21.9,8.2 +IRR,Irritability Scale,60-74,M,221,22.9,4.9 diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0004/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-e0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e537fd8e3acf9b1add14b833fa11c3106af5585 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0004/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-e0004/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0004/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-e0004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0004/task.toml b/tasks/psychometrics/psychometrics-norms-d2-e0004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d09af854d598119848402c1b6f41ef68610a09bc --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "eval"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-e0004/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-e0004/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..3078cd7fd397e183bf37f5162a7d5a5b36a3dbd5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0004/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C203.age", + "type": "int", + "value": 45, + "weight": 1.0 + }, + { + "path": "clients.C203.z", + "type": "number", + "value": -1.57, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C203.t_score", + "type": "number", + "value": 34.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C203.percentile", + "type": "number", + "value": 5.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C327.age", + "type": "int", + "value": 72, + "weight": 1.0 + }, + { + "path": "clients.C327.z", + "type": "number", + "value": 1.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C327.t_score", + "type": "number", + "value": 64.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C327.percentile", + "type": "number", + "value": 92.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C168.age", + "type": "int", + "value": 55, + "weight": 1.0 + }, + { + "path": "clients.C168.z", + "type": "number", + "value": 0.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C168.t_score", + "type": "number", + "value": 51.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C168.percentile", + "type": "number", + "value": 55.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C245.age", + "type": "int", + "value": 60, + "weight": 1.0 + }, + { + "path": "clients.C245.z", + "type": "number", + "value": 1.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C245.t_score", + "type": "number", + "value": 60.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C245.percentile", + "type": "number", + "value": 85.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C384.age", + "type": "int", + "value": 58, + "weight": 1.0 + }, + { + "path": "clients.C384.z", + "type": "number", + "value": 1.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C384.t_score", + "type": "number", + "value": 66.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C384.percentile", + "type": "number", + "value": 94.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C138.age", + "type": "int", + "value": 59, + "weight": 1.0 + }, + { + "path": "clients.C138.z", + "type": "number", + "value": 1.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C138.t_score", + "type": "number", + "value": 69.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C138.percentile", + "type": "number", + "value": 97.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C239", + "C295" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0004/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-e0004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-e0004/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-e0004/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-e0016/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..995cd7b7e0c3be3941a55ffcb3f64201a30358af --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C150,F,1959-05-02,2025-05-25,23,occupational health +C234,F,2009-08-23,2025-11-26,26,GP +C254,F,1990-08-04,2025-08-19,27,GP +C177,F,1965-08-13,2025-08-12,30,GP +C183,F,1946-08-07,2025-09-21,34,GP +C349,M,1987-05-17,2025-07-26,34,GP +C331,M,1953-09-09,2025-02-12,27,occupational health +C305,M,1973-05-17,2025-06-24,26,GP diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..9cedf13c55446e8de71f040a4476d53e5183711a --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,45-59,M,228,23.7,4.8 +FAT,Fatigue Scale,18-29,F,338,24.2,7.3 +FAT,Fatigue Scale,30-44,M,443,21.4,6.9 +FAT,Fatigue Scale,30-44,F,250,27.5,7.3 +FAT,Fatigue Scale,45-59,F,848,25.7,8.5 +FAT,Fatigue Scale,60-74,M,709,25.8,5.1 +FAT,Fatigue Scale,60-74,F,289,24.0,4.3 +FAT,Fatigue Scale,18-29,M,620,24.4,5.7 diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0016/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-e0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d53f08d6d2c321533ec8afa160b82861062f0544 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Fatigue Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0016/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-e0016/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0016/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-e0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0016/task.toml b/tasks/psychometrics/psychometrics-norms-d2-e0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d0219d7ed62608144c66737412ab18448d5ab6b --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "eval"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-e0016/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-e0016/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8d65164cc3d9349a14a34bbbc889ac8a87a0ea24 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-e0016/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C305.age", + "type": "int", + "value": 52, + "weight": 1.0 + }, + { + "path": "clients.C305.z", + "type": "number", + "value": 0.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C305.t_score", + "type": "number", + "value": 54.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C305.percentile", + "type": "number", + "value": 68.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C254.age", + "type": "int", + "value": 35, + "weight": 1.0 + }, + { + "path": "clients.C254.z", + "type": "number", + "value": -0.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C254.t_score", + "type": "number", + "value": 49.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C254.percentile", + "type": "number", + "value": 47.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C177.age", + "type": "int", + "value": 59, + "weight": 1.0 + }, + { + "path": "clients.C177.z", + "type": "number", + "value": 0.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C177.t_score", + "type": "number", + "value": 55.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C177.percentile", + "type": "number", + "value": 69.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C331.age", + "type": "int", + "value": 71, + "weight": 1.0 + }, + { + "path": "clients.C331.z", + "type": "number", + "value": 0.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C331.t_score", + "type": "number", + "value": 52.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C331.percentile", + "type": "number", + "value": 59.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C349.age", + "type": "int", + "value": 38, + "weight": 1.0 + }, + { + "path": "clients.C349.z", + "type": "number", + "value": 1.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C349.t_score", + "type": "number", + "value": 68.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C349.percentile", + "type": "number", + "value": 96.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C150.age", + "type": "int", + "value": 66, + "weight": 1.0 + }, + { + "path": "clients.C150.z", + "type": "number", + "value": -0.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C150.t_score", + "type": "number", + "value": 47.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C150.percentile", + "type": "number", + "value": 40.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C183", + "C234" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-e0016/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-e0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-e0016/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-e0016/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0004/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..d619e608b4a57b21e100725534e2e94c72199ed7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C308,F,1995-09-12,2025-04-10,25,GP +C388,M,1958-01-01,2025-06-13,42,occupational health +C259,M,1995-03-26,2025-03-23,47,occupational health +C220,M,1969-08-16,2025-09-13,39,self +C354,M,1950-08-13,2025-08-09,31,occupational health +C287,M,1946-01-12,2025-06-11,25,GP +C129,M,2007-12-24,2025-04-11,45,self +C201,M,2005-10-01,2025-09-24,39,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..648654609ea5c019ce75a8485b2b3c8e4a064698 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +WDR,Withdrawal Scale,18-29,M,801,30.3,8.0 +WDR,Withdrawal Scale,60-74,M,239,27.3,8.4 +WDR,Withdrawal Scale,30-44,F,561,32.8,5.1 +WDR,Withdrawal Scale,45-59,M,238,33.0,4.1 +WDR,Withdrawal Scale,18-29,F,635,31.5,5.5 +WDR,Withdrawal Scale,30-44,M,384,29.2,4.7 +WDR,Withdrawal Scale,60-74,F,777,31.7,6.3 +WDR,Withdrawal Scale,45-59,F,546,30.4,5.7 diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0004/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-t0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..094ef28a109548fa7dc6450c2d8d4c38d97b8217 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Withdrawal Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0004/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-t0004/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0004/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-t0004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0004/task.toml b/tasks/psychometrics/psychometrics-norms-d2-t0004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9c0a75a5dda73f8c17786e394055250b38de0a22 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-t0004/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-t0004/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1cf4d5d02bb38b4923b575db394ecbe298640445 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0004/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C354.age", + "type": "int", + "value": 74, + "weight": 1.0 + }, + { + "path": "clients.C354.z", + "type": "number", + "value": 0.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C354.t_score", + "type": "number", + "value": 54.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C354.percentile", + "type": "number", + "value": 67.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C388.age", + "type": "int", + "value": 67, + "weight": 1.0 + }, + { + "path": "clients.C388.z", + "type": "number", + "value": 1.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C388.t_score", + "type": "number", + "value": 67.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C388.percentile", + "type": "number", + "value": 96.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C308.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C308.z", + "type": "number", + "value": -1.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C308.t_score", + "type": "number", + "value": 38.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C308.percentile", + "type": "number", + "value": 11.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C201.age", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C201.z", + "type": "number", + "value": 1.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C201.t_score", + "type": "number", + "value": 60.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C201.percentile", + "type": "number", + "value": 86.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C259.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C259.z", + "type": "number", + "value": 2.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C259.t_score", + "type": "number", + "value": 70.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C259.percentile", + "type": "number", + "value": 98.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C220.age", + "type": "int", + "value": 56, + "weight": 1.0 + }, + { + "path": "clients.C220.z", + "type": "number", + "value": 1.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C220.t_score", + "type": "number", + "value": 64.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C220.percentile", + "type": "number", + "value": 92.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C129", + "C287" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0004/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-t0004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0004/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-t0004/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0016/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..fab7a1d433abc7d571681588eb11b244651a5609 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C392,F,1963-07-15,2025-02-15,25,self +C264,M,2006-03-08,2025-11-19,45,GP +C282,M,1995-07-22,2025-07-20,21,GP +C183,F,2009-03-23,2025-05-20,20,GP +C399,M,1943-01-11,2025-04-14,42,self +C230,M,1972-09-19,2025-08-28,18,occupational health +C102,M,1988-06-18,2025-04-08,29,GP +C172,F,1997-03-21,2025-10-05,24,self diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..bd81a703e397c055ae7d206f5ac6ad2f11bfb612 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,45-59,F,602,22.1,8.0 +IRR,Irritability Scale,30-44,M,434,22.4,7.3 +IRR,Irritability Scale,18-29,F,612,24.2,4.4 +IRR,Irritability Scale,60-74,M,417,18.6,4.7 +IRR,Irritability Scale,30-44,F,754,23.7,6.7 +IRR,Irritability Scale,45-59,M,469,24.5,7.7 +IRR,Irritability Scale,18-29,M,209,23.9,8.3 +IRR,Irritability Scale,60-74,F,265,21.8,7.0 diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0016/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-t0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e537fd8e3acf9b1add14b833fa11c3106af5585 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0016/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-t0016/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0016/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-t0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0016/task.toml b/tasks/psychometrics/psychometrics-norms-d2-t0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5af46d696e3874fce9c83a2e3ba13a6fb3d8035a --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-t0016/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-t0016/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d5138171d5406fe20c0f9b2bdd8d0277f2184b27 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0016/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C172.age", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C172.z", + "type": "number", + "value": -0.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C172.t_score", + "type": "number", + "value": 49.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C172.percentile", + "type": "number", + "value": 48.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C102.age", + "type": "int", + "value": 36, + "weight": 1.0 + }, + { + "path": "clients.C102.z", + "type": "number", + "value": 0.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C102.t_score", + "type": "number", + "value": 59.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C102.percentile", + "type": "number", + "value": 81.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C264.age", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C264.z", + "type": "number", + "value": 2.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C264.t_score", + "type": "number", + "value": 75.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C264.percentile", + "type": "number", + "value": 99.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C230.age", + "type": "int", + "value": 52, + "weight": 1.0 + }, + { + "path": "clients.C230.z", + "type": "number", + "value": -0.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C230.t_score", + "type": "number", + "value": 41.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C230.percentile", + "type": "number", + "value": 19.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C282.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C282.z", + "type": "number", + "value": -0.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C282.t_score", + "type": "number", + "value": 46.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C282.percentile", + "type": "number", + "value": 36.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C392.age", + "type": "int", + "value": 61, + "weight": 1.0 + }, + { + "path": "clients.C392.z", + "type": "number", + "value": 0.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C392.t_score", + "type": "number", + "value": 54.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C392.percentile", + "type": "number", + "value": 67.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C183", + "C399" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0016/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-t0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0016/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-t0016/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0028/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..0b21fbd4f550b41de01887aa5dbc39e9e9ab29cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C206,M,1980-04-23,2025-04-20,26,self +C197,F,1990-06-20,2025-08-14,38,GP +C296,F,1949-03-26,2025-04-06,34,GP +C251,F,1997-02-06,2025-03-18,39,GP +C376,M,1997-02-21,2025-02-06,18,GP +C123,M,2003-03-23,2025-08-10,27,occupational health +C286,M,1949-07-21,2025-05-18,15,self +C321,F,1952-01-23,2025-07-15,18,self diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..3c28a4af3b02eb63dcf1fde5b95e1c3cd7da41e1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,18-29,F,204,22.1,6.7 +FAT,Fatigue Scale,30-44,M,629,23.0,5.5 +FAT,Fatigue Scale,30-44,F,305,20.0,7.3 +FAT,Fatigue Scale,45-59,M,241,17.7,4.2 +FAT,Fatigue Scale,60-74,M,714,25.8,7.7 +FAT,Fatigue Scale,45-59,F,505,26.9,4.2 +FAT,Fatigue Scale,60-74,F,230,25.6,4.5 +FAT,Fatigue Scale,18-29,M,155,21.3,5.8 diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0028/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-t0028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d53f08d6d2c321533ec8afa160b82861062f0544 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Fatigue Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0028/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-t0028/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0028/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-t0028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0028/task.toml b/tasks/psychometrics/psychometrics-norms-d2-t0028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5dfe059444700b22aecb0f66f99a9f46613587ef --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-t0028/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-t0028/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..dac2923d04d64be904a89daaf319e21da65b42d6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0028/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C251.age", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C251.z", + "type": "number", + "value": 2.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C251.t_score", + "type": "number", + "value": 75.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C251.percentile", + "type": "number", + "value": 99.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C123.age", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C123.z", + "type": "number", + "value": 0.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C123.t_score", + "type": "number", + "value": 59.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C123.percentile", + "type": "number", + "value": 83.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C321.age", + "type": "int", + "value": 73, + "weight": 1.0 + }, + { + "path": "clients.C321.z", + "type": "number", + "value": -1.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C321.t_score", + "type": "number", + "value": 33.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C321.percentile", + "type": "number", + "value": 4.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C197.age", + "type": "int", + "value": 35, + "weight": 1.0 + }, + { + "path": "clients.C197.z", + "type": "number", + "value": 2.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C197.t_score", + "type": "number", + "value": 74.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C197.percentile", + "type": "number", + "value": 99.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C206.age", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C206.z", + "type": "number", + "value": 0.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C206.t_score", + "type": "number", + "value": 55.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C206.percentile", + "type": "number", + "value": 70.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C376.age", + "type": "int", + "value": 27, + "weight": 1.0 + }, + { + "path": "clients.C376.z", + "type": "number", + "value": -0.57, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C376.t_score", + "type": "number", + "value": 44.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C376.percentile", + "type": "number", + "value": 28.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C286", + "C296" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0028/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-t0028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0028/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-t0028/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0040/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..1115d0b2a2afc3e06cf2b3c7e36fb9bdf21cd172 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C324,F,1965-08-07,2025-08-06,29,self +C110,M,1942-10-03,2025-08-18,31,occupational health +C370,F,1979-08-16,2025-02-16,16,GP +C350,F,1963-04-12,2025-11-17,24,GP +C189,F,1964-01-23,2025-09-19,7,GP +C273,M,1978-03-13,2025-09-15,32,occupational health +C159,M,1943-06-16,2025-09-28,22,GP +C344,M,1995-07-28,2025-10-14,32,GP diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..cd5bab337dc90937b60d34d17f536fba9cb91b10 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +WDR,Withdrawal Scale,60-74,M,359,17.5,6.3 +WDR,Withdrawal Scale,30-44,M,600,22.2,6.4 +WDR,Withdrawal Scale,18-29,M,196,19.8,5.1 +WDR,Withdrawal Scale,45-59,M,702,22.7,4.8 +WDR,Withdrawal Scale,45-59,F,896,22.0,7.0 +WDR,Withdrawal Scale,60-74,F,242,17.3,7.2 +WDR,Withdrawal Scale,30-44,F,217,22.0,4.0 +WDR,Withdrawal Scale,18-29,F,274,22.6,4.1 diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0040/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-t0040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..094ef28a109548fa7dc6450c2d8d4c38d97b8217 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Withdrawal Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0040/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-t0040/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0040/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-t0040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0040/task.toml b/tasks/psychometrics/psychometrics-norms-d2-t0040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c6a0d2e6ef25e73de1440b44b98a3ade2b3afe48 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-t0040/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-t0040/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..04af617607056561926aff737c001169d92eb872 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0040/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C370.age", + "type": "int", + "value": 45, + "weight": 1.0 + }, + { + "path": "clients.C370.z", + "type": "number", + "value": -0.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C370.t_score", + "type": "number", + "value": 41.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C370.percentile", + "type": "number", + "value": 19.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C273.age", + "type": "int", + "value": 47, + "weight": 1.0 + }, + { + "path": "clients.C273.z", + "type": "number", + "value": 1.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C273.t_score", + "type": "number", + "value": 69.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C273.percentile", + "type": "number", + "value": 97.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C344.age", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "clients.C344.z", + "type": "number", + "value": 1.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C344.t_score", + "type": "number", + "value": 65.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C344.percentile", + "type": "number", + "value": 93.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C189.age", + "type": "int", + "value": 61, + "weight": 1.0 + }, + { + "path": "clients.C189.z", + "type": "number", + "value": -1.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C189.t_score", + "type": "number", + "value": 35.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C189.percentile", + "type": "number", + "value": 7.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C324.age", + "type": "int", + "value": 59, + "weight": 1.0 + }, + { + "path": "clients.C324.z", + "type": "number", + "value": 1.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C324.t_score", + "type": "number", + "value": 60.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C324.percentile", + "type": "number", + "value": 84.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C350.age", + "type": "int", + "value": 62, + "weight": 1.0 + }, + { + "path": "clients.C350.z", + "type": "number", + "value": 0.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C350.t_score", + "type": "number", + "value": 59.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C350.percentile", + "type": "number", + "value": 82.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C110", + "C159" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0040/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-t0040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0040/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-t0040/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0052/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..bde19e6fba1b7e354466d31cc7142cecebf84fb4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C166,F,1955-03-10,2025-07-07,33,self +C144,F,1971-02-20,2025-08-21,34,self +C102,M,2009-03-06,2025-05-12,37,GP +C185,F,2008-12-28,2025-06-27,30,occupational health +C233,M,2004-12-14,2025-05-09,26,occupational health +C145,F,2005-05-22,2025-04-15,30,occupational health +C162,F,1995-10-01,2025-09-27,43,occupational health +C133,M,1975-02-22,2025-02-24,32,GP diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..ee06a0b58c809fda69cb2381349c031e6ca881a2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,18-29,F,447,30.8,5.7 +IRR,Irritability Scale,30-44,F,547,31.4,5.4 +IRR,Irritability Scale,60-74,F,273,29.4,6.6 +IRR,Irritability Scale,60-74,M,297,28.2,4.2 +IRR,Irritability Scale,18-29,M,690,29.3,5.5 +IRR,Irritability Scale,30-44,M,608,25.7,4.3 +IRR,Irritability Scale,45-59,M,356,24.7,5.5 +IRR,Irritability Scale,45-59,F,200,32.1,4.7 diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0052/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-t0052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e537fd8e3acf9b1add14b833fa11c3106af5585 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0052/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-t0052/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0052/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-t0052/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0052/task.toml b/tasks/psychometrics/psychometrics-norms-d2-t0052/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f47edecb19746c16e3a3d3584a4e31b5cc70563c --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-t0052/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-t0052/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..0b027d209d9b72ca1f371c6e323e467c1fed2173 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0052/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C233.age", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "clients.C233.z", + "type": "number", + "value": -0.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C233.t_score", + "type": "number", + "value": 44.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C233.percentile", + "type": "number", + "value": 27.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C144.age", + "type": "int", + "value": 54, + "weight": 1.0 + }, + { + "path": "clients.C144.z", + "type": "number", + "value": 0.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C144.t_score", + "type": "number", + "value": 54.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C144.percentile", + "type": "number", + "value": 65.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C145.age", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C145.z", + "type": "number", + "value": -0.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C145.t_score", + "type": "number", + "value": 48.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C145.percentile", + "type": "number", + "value": 44.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C166.age", + "type": "int", + "value": 70, + "weight": 1.0 + }, + { + "path": "clients.C166.z", + "type": "number", + "value": 0.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C166.t_score", + "type": "number", + "value": 55.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C166.percentile", + "type": "number", + "value": 70.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C162.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C162.z", + "type": "number", + "value": 2.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C162.t_score", + "type": "number", + "value": 71.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C162.percentile", + "type": "number", + "value": 98.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C133.age", + "type": "int", + "value": 50, + "weight": 1.0 + }, + { + "path": "clients.C133.z", + "type": "number", + "value": 1.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C133.t_score", + "type": "number", + "value": 63.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C133.percentile", + "type": "number", + "value": 90.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C102", + "C185" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0052/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-t0052/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0052/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-t0052/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0064/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..3da1494822cec9de14cb965f3d1aee5185735342 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C358,F,1993-03-23,2025-03-13,19,occupational health +C129,M,1969-01-13,2025-02-09,22,self +C294,F,1995-06-22,2025-06-19,28,GP +C341,F,1943-06-07,2025-09-02,32,GP +C271,M,1967-06-06,2025-11-28,16,self +C125,M,1943-10-28,2025-11-07,28,occupational health +C306,M,1967-05-18,2025-04-20,17,occupational health +C314,F,1997-10-25,2025-03-16,15,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..63e60e6b32a498158905b6fad5f90fa38941a19f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,60-74,F,136,21.5,6.1 +FAT,Fatigue Scale,18-29,M,210,16.5,6.0 +FAT,Fatigue Scale,45-59,M,349,20.7,5.1 +FAT,Fatigue Scale,30-44,M,495,19.0,4.1 +FAT,Fatigue Scale,18-29,F,223,19.8,4.6 +FAT,Fatigue Scale,45-59,F,493,22.5,7.5 +FAT,Fatigue Scale,60-74,M,591,20.7,6.9 +FAT,Fatigue Scale,30-44,F,134,18.1,5.7 diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0064/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-t0064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d53f08d6d2c321533ec8afa160b82861062f0544 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Fatigue Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0064/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-t0064/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0064/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-t0064/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0064/task.toml b/tasks/psychometrics/psychometrics-norms-d2-t0064/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8079bf0071e6033163411ef443196f1d9f91bbf6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-t0064/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-t0064/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..235fdb88f9347ae76fb983602422efe6c49c5d6d --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0064/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C294.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C294.z", + "type": "number", + "value": 1.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C294.t_score", + "type": "number", + "value": 67.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C294.percentile", + "type": "number", + "value": 96.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C314.age", + "type": "int", + "value": 27, + "weight": 1.0 + }, + { + "path": "clients.C314.z", + "type": "number", + "value": -1.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C314.t_score", + "type": "number", + "value": 39.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C314.percentile", + "type": "number", + "value": 14.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C358.age", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "clients.C358.z", + "type": "number", + "value": 0.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C358.t_score", + "type": "number", + "value": 51.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C358.percentile", + "type": "number", + "value": 56.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C129.age", + "type": "int", + "value": 56, + "weight": 1.0 + }, + { + "path": "clients.C129.z", + "type": "number", + "value": 0.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C129.t_score", + "type": "number", + "value": 52.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C129.percentile", + "type": "number", + "value": 60.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C271.age", + "type": "int", + "value": 58, + "weight": 1.0 + }, + { + "path": "clients.C271.z", + "type": "number", + "value": -0.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C271.t_score", + "type": "number", + "value": 40.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C271.percentile", + "type": "number", + "value": 17.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C306.age", + "type": "int", + "value": 57, + "weight": 1.0 + }, + { + "path": "clients.C306.z", + "type": "number", + "value": -0.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C306.t_score", + "type": "number", + "value": 42.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C306.percentile", + "type": "number", + "value": 23.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C125", + "C341" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0064/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-t0064/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0064/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-t0064/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0076/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..bde3099a19af17dd23c974ea0ff49dfe7e305817 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/clients.csv @@ -0,0 +1,9 @@ +client_id,sex,date_of_birth,test_date,raw_score,referral +C102,F,1957-06-23,2025-02-20,15,occupational health +C282,F,1965-10-27,2025-10-25,14,GP +C361,M,1943-01-25,2025-08-04,33,GP +C321,M,1978-06-14,2025-07-05,20,GP +C138,M,1986-12-20,2025-11-21,22,occupational health +C123,F,1968-08-15,2025-03-21,8,self +C209,M,1973-08-23,2025-02-22,25,self +C246,M,1950-04-02,2025-05-12,10,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..9605d4d313bce1f266d9099f1a14b379e28a046f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/norms.csv @@ -0,0 +1,9 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,30-44,M,182,15.7,8.2 +IRR,Irritability Scale,45-59,M,570,15.1,6.5 +IRR,Irritability Scale,45-59,F,360,12.1,7.5 +IRR,Irritability Scale,60-74,F,590,20.6,4.9 +IRR,Irritability Scale,60-74,M,817,12.2,4.4 +IRR,Irritability Scale,30-44,F,734,13.7,8.3 +IRR,Irritability Scale,18-29,M,325,15.5,8.4 +IRR,Irritability Scale,18-29,F,616,17.4,8.3 diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2e835c8fa02e898c0bc5815c805e4615e24e307f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/environment/workdir/norms_guide.md @@ -0,0 +1,15 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0076/instruction.md b/tasks/psychometrics/psychometrics-norms-d2-t0076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e537fd8e3acf9b1add14b833fa11c3106af5585 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/instruction.md @@ -0,0 +1,16 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on the Irritability Scale. `norms.csv` is the norm table and `norms_guide.md` says how to use it. + +Convert every raw score using the norm group that matches the client's age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0076/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d2-t0076/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0076/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d2-t0076/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0076/task.toml b/tasks/psychometrics/psychometrics-norms-d2-t0076/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c966117bd3c0afe092a8c21540c3ac45c9b29857 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d2-t0076/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d2-t0076/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6644d23d7c7d84599651f6ae3812b11d683d47f2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d2-t0076/tests/checks.json @@ -0,0 +1,174 @@ +[ + { + "path": "clients.C102.age", + "type": "int", + "value": 67, + "weight": 1.0 + }, + { + "path": "clients.C102.z", + "type": "number", + "value": -1.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C102.t_score", + "type": "number", + "value": 38.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C102.percentile", + "type": "number", + "value": 12.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C282.age", + "type": "int", + "value": 59, + "weight": 1.0 + }, + { + "path": "clients.C282.z", + "type": "number", + "value": 0.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C282.t_score", + "type": "number", + "value": 52.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C282.percentile", + "type": "number", + "value": 60.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C321.age", + "type": "int", + "value": 47, + "weight": 1.0 + }, + { + "path": "clients.C321.z", + "type": "number", + "value": 0.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C321.t_score", + "type": "number", + "value": 57.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C321.percentile", + "type": "number", + "value": 77.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C209.age", + "type": "int", + "value": 51, + "weight": 1.0 + }, + { + "path": "clients.C209.z", + "type": "number", + "value": 1.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C209.t_score", + "type": "number", + "value": 65.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C209.percentile", + "type": "number", + "value": 93.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C123.age", + "type": "int", + "value": 56, + "weight": 1.0 + }, + { + "path": "clients.C123.z", + "type": "number", + "value": -0.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C123.t_score", + "type": "number", + "value": 44.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C123.percentile", + "type": "number", + "value": 29.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C138.age", + "type": "int", + "value": 38, + "weight": 1.0 + }, + { + "path": "clients.C138.z", + "type": "number", + "value": 0.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C138.t_score", + "type": "number", + "value": 57.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C138.percentile", + "type": "number", + "value": 77.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C246", + "C361" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d2-t0076/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d2-t0076/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d2-t0076/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d2-t0076/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-e0008/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..bad83c585b9f045b488d7d99c253081ebf4ae88c --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C324,F,1995-10-17,2025-10-15,FAT,33,GP +C152,F,1983-07-23,2025-10-06,IRR,37,occupational health +C388,F,2006-03-23,2025-11-04,IRR,29,occupational health +C324,F,1995-10-17,2025-10-15,IRR,46,occupational health +C152,F,1983-07-23,2025-10-06,FAT,31,self +C251,F,1949-02-13,2025-04-12,IRR,26,GP +C371,F,1985-11-19,2025-06-05,IRR,26,self +C388,F,2006-03-23,2025-11-04,FAT,24,occupational health +C371,F,1985-11-19,2025-06-05,FAT,33,occupational health +C251,F,1949-02-13,2025-04-12,FAT,28,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..b6c5f9afc8416e00c946ec8f8969d50a891e167b --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,18-29,M,155,23.5,4.5 +WDR,Withdrawal Scale,60-74,F,630,28.2,8.0 +IRR,Irritability Scale,45-59,F,252,27.7,5.3 +IRR,Irritability Scale,18-29,F,585,26.4,7.7 +FAT,Fatigue Scale,60-74,F,467,30.7,7.8 +WDR,Withdrawal Scale,45-59,M,750,29.9,8.4 +WDR,Withdrawal Scale,60-74,M,204,30.3,4.7 +IRR,Irritability Scale,30-44,F,716,25.7,8.3 +WDR,Withdrawal Scale,45-59,F,635,26.2,6.7 +IRR,Irritability Scale,60-74,F,324,21.9,7.2 +FAT,Fatigue Scale,18-29,F,772,26.0,6.1 +FAT,Fatigue Scale,60-74,M,250,30.6,4.8 +FAT,Fatigue Scale,45-59,F,328,23.3,5.6 +FAT,Fatigue Scale,30-44,F,201,27.5,4.4 +WDR,Withdrawal Scale,30-44,M,144,26.6,5.0 +FAT,Fatigue Scale,30-44,M,162,22.3,4.1 +IRR,Irritability Scale,60-74,M,128,21.5,5.0 +WDR,Withdrawal Scale,30-44,F,790,33.1,6.2 +IRR,Irritability Scale,45-59,M,747,27.4,4.1 +WDR,Withdrawal Scale,18-29,M,385,29.5,6.1 +FAT,Fatigue Scale,45-59,M,548,22.9,7.3 +IRR,Irritability Scale,18-29,M,766,24.3,5.8 +IRR,Irritability Scale,30-44,M,578,22.7,4.6 +WDR,Withdrawal Scale,18-29,F,863,30.2,8.3 diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0008/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-e0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0008/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-e0008/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0008/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-e0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0008/task.toml b/tasks/psychometrics/psychometrics-norms-d3-e0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b53b038ab79b0ed5e94e589fbabbfab009a8d4c --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "eval"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-e0008/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-e0008/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8bd6e2185f3df9c8d2ddbd34b5a699785ec80234 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0008/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "clients.C324.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C324.scales.FAT.z", + "type": "number", + "value": 1.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C324.scales.FAT.t_score", + "type": "number", + "value": 61.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C324.scales.FAT.percentile", + "type": "number", + "value": 87.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C324.scales.FAT.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C324.scales.IRR.z", + "type": "number", + "value": 2.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C324.scales.IRR.t_score", + "type": "number", + "value": 75.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C324.scales.IRR.percentile", + "type": "number", + "value": 99.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C324.scales.IRR.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C388.age", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C388.scales.FAT.z", + "type": "number", + "value": -0.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C388.scales.FAT.t_score", + "type": "number", + "value": 46.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C388.scales.FAT.percentile", + "type": "number", + "value": 37.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C388.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C388.scales.IRR.z", + "type": "number", + "value": 0.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C388.scales.IRR.t_score", + "type": "number", + "value": 53.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C388.scales.IRR.percentile", + "type": "number", + "value": 63.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C388.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C152.age", + "type": "int", + "value": 42, + "weight": 1.0 + }, + { + "path": "clients.C152.scales.FAT.z", + "type": "number", + "value": 0.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C152.scales.FAT.t_score", + "type": "number", + "value": 58.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C152.scales.FAT.percentile", + "type": "number", + "value": 78.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C152.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C152.scales.IRR.z", + "type": "number", + "value": 1.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C152.scales.IRR.t_score", + "type": "number", + "value": 63.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C152.scales.IRR.percentile", + "type": "number", + "value": 91.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C152.scales.IRR.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C371.age", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "clients.C371.scales.FAT.z", + "type": "number", + "value": 1.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C371.scales.FAT.t_score", + "type": "number", + "value": 62.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C371.scales.FAT.percentile", + "type": "number", + "value": 89.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C371.scales.FAT.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C371.scales.IRR.z", + "type": "number", + "value": 0.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C371.scales.IRR.t_score", + "type": "number", + "value": 50.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C371.scales.IRR.percentile", + "type": "number", + "value": 51.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C371.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C251" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [ + "C152:IRR", + "C324:FAT", + "C324:IRR", + "C371:FAT" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0008/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-e0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-e0008/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-e0008/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-e0020/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..ded39575085a5077b387faf8a0a0ba9b2c3f5546 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C161,F,1965-03-16,2025-03-14,IRR,21,self +C336,M,1989-05-21,2025-06-25,FAT,34,GP +C313,F,1946-07-18,2025-07-27,FAT,22,GP +C187,F,1982-02-27,2025-09-14,IRR,21,self +C336,M,1989-05-21,2025-06-25,IRR,33,self +C229,F,1987-01-18,2025-04-13,IRR,12,occupational health +C187,F,1982-02-27,2025-09-14,FAT,26,self +C229,F,1987-01-18,2025-04-13,FAT,13,occupational health +C313,F,1946-07-18,2025-07-27,IRR,30,GP +C161,F,1965-03-16,2025-03-14,FAT,15,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..027e1353b6d6c4aedf429cbbb31b9d8bad3e5ef6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,30-44,F,616,14.2,4.9 +IRR,Irritability Scale,18-29,F,845,20.8,7.0 +WDR,Withdrawal Scale,60-74,F,483,15.9,8.1 +FAT,Fatigue Scale,60-74,F,431,12.4,6.7 +FAT,Fatigue Scale,18-29,M,771,16.2,7.3 +FAT,Fatigue Scale,45-59,M,405,17.9,4.7 +FAT,Fatigue Scale,45-59,F,689,12.3,4.5 +IRR,Irritability Scale,30-44,F,418,20.1,6.2 +WDR,Withdrawal Scale,30-44,M,680,22.0,6.8 +IRR,Irritability Scale,60-74,M,420,18.2,4.1 +IRR,Irritability Scale,45-59,F,433,18.9,8.4 +WDR,Withdrawal Scale,45-59,M,500,23.8,4.7 +FAT,Fatigue Scale,60-74,M,302,11.7,5.3 +WDR,Withdrawal Scale,18-29,F,400,22.2,8.0 +IRR,Irritability Scale,30-44,M,884,21.8,4.6 +IRR,Irritability Scale,45-59,M,322,17.1,4.7 +WDR,Withdrawal Scale,60-74,M,601,19.6,5.0 +WDR,Withdrawal Scale,45-59,F,456,25.5,7.0 +IRR,Irritability Scale,60-74,F,862,19.7,4.9 +FAT,Fatigue Scale,18-29,F,313,14.9,6.0 +WDR,Withdrawal Scale,18-29,M,239,19.7,5.6 +WDR,Withdrawal Scale,30-44,F,825,24.6,6.9 +IRR,Irritability Scale,18-29,M,449,21.5,6.7 +FAT,Fatigue Scale,30-44,M,468,12.2,8.4 diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0020/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-e0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0020/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-e0020/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0020/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-e0020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0020/task.toml b/tasks/psychometrics/psychometrics-norms-d3-e0020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b1f098088d14b96ef23f135427ba18afd3bdeae3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "eval"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-e0020/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-e0020/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..25ad2085bd3300a6f8528eb112ea0adb3a03657a --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-e0020/tests/checks.json @@ -0,0 +1,262 @@ +[ + { + "path": "clients.C187.age", + "type": "int", + "value": 43, + "weight": 1.0 + }, + { + "path": "clients.C187.scales.FAT.z", + "type": "number", + "value": 2.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C187.scales.FAT.t_score", + "type": "number", + "value": 74.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C187.scales.FAT.percentile", + "type": "number", + "value": 99.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C187.scales.FAT.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C187.scales.IRR.z", + "type": "number", + "value": 0.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C187.scales.IRR.t_score", + "type": "number", + "value": 51.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C187.scales.IRR.percentile", + "type": "number", + "value": 55.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C187.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C336.age", + "type": "int", + "value": 36, + "weight": 1.0 + }, + { + "path": "clients.C336.scales.FAT.z", + "type": "number", + "value": 2.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C336.scales.FAT.t_score", + "type": "number", + "value": 76.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C336.scales.FAT.percentile", + "type": "number", + "value": 99.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C336.scales.FAT.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C336.scales.IRR.z", + "type": "number", + "value": 2.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C336.scales.IRR.t_score", + "type": "number", + "value": 74.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C336.scales.IRR.percentile", + "type": "number", + "value": 99.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C336.scales.IRR.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C229.age", + "type": "int", + "value": 38, + "weight": 1.0 + }, + { + "path": "clients.C229.scales.FAT.z", + "type": "number", + "value": -0.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C229.scales.FAT.t_score", + "type": "number", + "value": 47.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C229.scales.FAT.percentile", + "type": "number", + "value": 40.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C229.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C229.scales.IRR.z", + "type": "number", + "value": -1.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C229.scales.IRR.t_score", + "type": "number", + "value": 36.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C229.scales.IRR.percentile", + "type": "number", + "value": 9.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C229.scales.IRR.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C161.age", + "type": "int", + "value": 59, + "weight": 1.0 + }, + { + "path": "clients.C161.scales.FAT.z", + "type": "number", + "value": 0.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C161.scales.FAT.t_score", + "type": "number", + "value": 56.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C161.scales.FAT.percentile", + "type": "number", + "value": 72.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C161.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C161.scales.IRR.z", + "type": "number", + "value": 0.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C161.scales.IRR.t_score", + "type": "number", + "value": 52.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C161.scales.IRR.percentile", + "type": "number", + "value": 59.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C161.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C313" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [ + "C187:FAT", + "C336:FAT", + "C336:IRR" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-e0020/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-e0020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-e0020/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-e0020/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0008/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..c4b0a07351970199c647d3042f1000513b550928 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C357,F,1943-03-01,2025-04-03,WDR,28,GP +C207,M,1980-06-12,2025-06-09,ATT,18,GP +C207,M,1980-06-12,2025-06-09,WDR,36,GP +C216,F,1985-07-17,2025-03-11,WDR,20,self +C298,M,1964-02-12,2025-09-03,ATT,32,self +C231,F,1957-06-21,2025-06-14,ATT,15,GP +C298,M,1964-02-12,2025-09-03,WDR,41,self +C357,F,1943-03-01,2025-04-03,ATT,35,occupational health +C216,F,1985-07-17,2025-03-11,ATT,19,GP +C231,F,1957-06-21,2025-06-14,WDR,27,self diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..20569ed7d043a3caedeead5f101ba611ce170469 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,18-29,F,734,30.1,5.1 +ATT,Attention Difficulties Scale,45-59,M,176,23.8,8.2 +ATT,Attention Difficulties Scale,60-74,M,708,18.5,6.3 +WDR,Withdrawal Scale,30-44,M,301,26.0,7.5 +ATT,Attention Difficulties Scale,60-74,F,618,16.3,4.5 +WDR,Withdrawal Scale,30-44,F,864,29.6,7.1 +WDR,Withdrawal Scale,18-29,M,775,25.4,6.8 +IRR,Irritability Scale,18-29,M,264,29.7,4.7 +IRR,Irritability Scale,30-44,F,408,31.9,8.3 +WDR,Withdrawal Scale,60-74,M,766,30.4,4.3 +IRR,Irritability Scale,60-74,M,246,33.3,5.4 +ATT,Attention Difficulties Scale,18-29,M,738,19.6,4.4 +ATT,Attention Difficulties Scale,30-44,F,580,19.2,7.9 +WDR,Withdrawal Scale,18-29,F,376,25.4,6.5 +ATT,Attention Difficulties Scale,18-29,F,388,21.0,5.6 +IRR,Irritability Scale,30-44,M,337,29.6,5.0 +IRR,Irritability Scale,45-59,M,120,31.8,4.6 +WDR,Withdrawal Scale,60-74,F,486,30.5,4.3 +WDR,Withdrawal Scale,45-59,M,581,28.9,6.7 +IRR,Irritability Scale,60-74,F,480,31.8,5.6 +ATT,Attention Difficulties Scale,45-59,F,438,17.8,4.9 +WDR,Withdrawal Scale,45-59,F,163,27.3,6.5 +ATT,Attention Difficulties Scale,30-44,M,767,20.6,5.3 +IRR,Irritability Scale,45-59,F,710,28.8,6.1 diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0008/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0008/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-t0008/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0008/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-t0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0008/task.toml b/tasks/psychometrics/psychometrics-norms-d3-t0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bf4edf6215770e37346fafd3071f83174670ff88 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-t0008/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-t0008/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..82c77ac4e14a57383dc51f63c0f0e425d6db499b --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0008/tests/checks.json @@ -0,0 +1,262 @@ +[ + { + "path": "clients.C231.age", + "type": "int", + "value": 67, + "weight": 1.0 + }, + { + "path": "clients.C231.scales.WDR.z", + "type": "number", + "value": -0.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C231.scales.WDR.t_score", + "type": "number", + "value": 41.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C231.scales.WDR.percentile", + "type": "number", + "value": 20.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C231.scales.WDR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C231.scales.ATT.z", + "type": "number", + "value": -0.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C231.scales.ATT.t_score", + "type": "number", + "value": 47.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C231.scales.ATT.percentile", + "type": "number", + "value": 38.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C231.scales.ATT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C298.age", + "type": "int", + "value": 61, + "weight": 1.0 + }, + { + "path": "clients.C298.scales.WDR.z", + "type": "number", + "value": 2.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C298.scales.WDR.t_score", + "type": "number", + "value": 74.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C298.scales.WDR.percentile", + "type": "number", + "value": 99.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C298.scales.WDR.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C298.scales.ATT.z", + "type": "number", + "value": 2.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C298.scales.ATT.t_score", + "type": "number", + "value": 71.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C298.scales.ATT.percentile", + "type": "number", + "value": 98.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C298.scales.ATT.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C207.age", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C207.scales.WDR.z", + "type": "number", + "value": 1.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C207.scales.WDR.t_score", + "type": "number", + "value": 63.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C207.scales.WDR.percentile", + "type": "number", + "value": 90.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C207.scales.WDR.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C207.scales.ATT.z", + "type": "number", + "value": -0.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C207.scales.ATT.t_score", + "type": "number", + "value": 45.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C207.scales.ATT.percentile", + "type": "number", + "value": 31.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C207.scales.ATT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C216.age", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "clients.C216.scales.WDR.z", + "type": "number", + "value": -1.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C216.scales.WDR.t_score", + "type": "number", + "value": 36.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C216.scales.WDR.percentile", + "type": "number", + "value": 8.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C216.scales.WDR.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C216.scales.ATT.z", + "type": "number", + "value": -0.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C216.scales.ATT.t_score", + "type": "number", + "value": 49.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C216.scales.ATT.percentile", + "type": "number", + "value": 49.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C216.scales.ATT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C357" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [ + "C207:WDR", + "C298:ATT", + "C298:WDR" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0008/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-t0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0008/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-t0008/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0020/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..567714334b4310cb7bde34f3255d0f3719b4c9be --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C281,F,1995-09-21,2025-09-18,ATT,23,occupational health +C104,F,1983-09-27,2025-06-25,FAT,26,self +C355,F,2010-08-07,2025-10-22,ATT,18,self +C104,F,1983-09-27,2025-06-25,ATT,9,occupational health +C384,M,2006-07-16,2025-07-03,FAT,19,GP +C317,F,1961-05-12,2025-10-16,ATT,20,self +C281,F,1995-09-21,2025-09-18,FAT,25,occupational health +C317,F,1961-05-12,2025-10-16,FAT,25,GP +C355,F,2010-08-07,2025-10-22,FAT,30,GP +C384,M,2006-07-16,2025-07-03,ATT,8,GP diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..9aab7244120dfb099e0ec3c65d370e997248e624 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,30-44,M,245,19.5,6.6 +WDR,Withdrawal Scale,30-44,M,603,16.4,8.0 +ATT,Attention Difficulties Scale,45-59,F,446,20.0,7.9 +WDR,Withdrawal Scale,18-29,F,251,16.2,6.4 +ATT,Attention Difficulties Scale,18-29,M,875,16.7,5.3 +FAT,Fatigue Scale,30-44,F,165,23.0,5.4 +WDR,Withdrawal Scale,18-29,M,870,14.9,5.4 +WDR,Withdrawal Scale,30-44,F,591,18.2,8.0 +WDR,Withdrawal Scale,60-74,F,896,18.1,6.6 +FAT,Fatigue Scale,18-29,M,331,19.5,4.4 +FAT,Fatigue Scale,60-74,M,550,26.8,4.7 +WDR,Withdrawal Scale,45-59,F,227,13.9,6.6 +ATT,Attention Difficulties Scale,60-74,F,131,16.8,4.5 +FAT,Fatigue Scale,45-59,M,496,20.0,5.4 +FAT,Fatigue Scale,45-59,F,790,21.5,7.0 +ATT,Attention Difficulties Scale,18-29,F,878,17.3,6.7 +ATT,Attention Difficulties Scale,30-44,F,630,17.4,8.1 +WDR,Withdrawal Scale,45-59,M,252,20.2,8.0 +FAT,Fatigue Scale,18-29,F,253,21.6,4.5 +FAT,Fatigue Scale,60-74,F,375,24.7,4.7 +ATT,Attention Difficulties Scale,60-74,M,613,15.7,6.3 +ATT,Attention Difficulties Scale,30-44,M,344,15.5,7.4 +WDR,Withdrawal Scale,60-74,M,435,16.5,8.4 +ATT,Attention Difficulties Scale,45-59,M,642,11.6,4.4 diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0020/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-t0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0020/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-t0020/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0020/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-t0020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0020/task.toml b/tasks/psychometrics/psychometrics-norms-d3-t0020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c6e2c7ecc045438e74e3e79848d9ba346e85343d --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-t0020/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-t0020/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6ff79d09a87a3914d2a3f1e57bd86176e5f23532 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0020/tests/checks.json @@ -0,0 +1,258 @@ +[ + { + "path": "clients.C104.age", + "type": "int", + "value": 41, + "weight": 1.0 + }, + { + "path": "clients.C104.scales.ATT.z", + "type": "number", + "value": -1.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C104.scales.ATT.t_score", + "type": "number", + "value": 39.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C104.scales.ATT.percentile", + "type": "number", + "value": 15.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C104.scales.ATT.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C104.scales.FAT.z", + "type": "number", + "value": 0.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C104.scales.FAT.t_score", + "type": "number", + "value": 55.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C104.scales.FAT.percentile", + "type": "number", + "value": 71.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C104.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C384.age", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C384.scales.ATT.z", + "type": "number", + "value": -1.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C384.scales.ATT.t_score", + "type": "number", + "value": 33.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C384.scales.ATT.percentile", + "type": "number", + "value": 5.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C384.scales.ATT.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C384.scales.FAT.z", + "type": "number", + "value": -0.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C384.scales.FAT.t_score", + "type": "number", + "value": 48.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C384.scales.FAT.percentile", + "type": "number", + "value": 45.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C384.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C281.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C281.scales.ATT.z", + "type": "number", + "value": 0.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C281.scales.ATT.t_score", + "type": "number", + "value": 58.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C281.scales.ATT.percentile", + "type": "number", + "value": 80.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C281.scales.ATT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C281.scales.FAT.z", + "type": "number", + "value": 0.76, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C281.scales.FAT.t_score", + "type": "number", + "value": 57.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C281.scales.FAT.percentile", + "type": "number", + "value": 77.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C281.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C317.age", + "type": "int", + "value": 64, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.ATT.z", + "type": "number", + "value": 0.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.ATT.t_score", + "type": "number", + "value": 57.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.ATT.percentile", + "type": "number", + "value": 76.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.ATT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C317.scales.FAT.z", + "type": "number", + "value": 0.06, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.FAT.t_score", + "type": "number", + "value": 50.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.FAT.percentile", + "type": "number", + "value": 52.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C355" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0020/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-t0020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0020/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-t0020/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0032/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..01215749dcfcde8616b7fdb8032bd77beb6bb2a3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C262,M,1967-02-08,2025-08-01,WDR,32,GP +C179,M,2008-10-26,2025-11-11,FAT,28,self +C179,M,2008-10-26,2025-11-11,WDR,29,occupational health +C234,F,1978-09-20,2025-10-27,WDR,16,occupational health +C349,M,1980-06-21,2025-06-20,FAT,24,self +C349,M,1980-06-21,2025-06-20,WDR,20,GP +C350,M,1978-11-25,2025-02-03,WDR,16,occupational health +C350,M,1978-11-25,2025-02-03,FAT,8,occupational health +C234,F,1978-09-20,2025-10-27,FAT,28,occupational health +C262,M,1967-02-08,2025-08-01,FAT,19,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..b9008d4b5744de25a06f5906e0b8437855acda46 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,45-59,M,595,18.0,5.6 +WDR,Withdrawal Scale,18-29,M,172,19.8,4.2 +WDR,Withdrawal Scale,18-29,F,179,22.0,7.2 +WDR,Withdrawal Scale,30-44,M,611,22.7,5.5 +FAT,Fatigue Scale,45-59,F,122,22.4,7.2 +WDR,Withdrawal Scale,30-44,F,720,22.3,7.3 +IRR,Irritability Scale,30-44,F,247,17.6,5.0 +WDR,Withdrawal Scale,60-74,M,587,16.1,4.2 +WDR,Withdrawal Scale,60-74,F,475,16.9,7.7 +FAT,Fatigue Scale,30-44,M,555,22.3,4.4 +FAT,Fatigue Scale,30-44,F,378,20.2,8.4 +FAT,Fatigue Scale,18-29,M,561,21.0,6.6 +IRR,Irritability Scale,30-44,M,793,16.4,6.0 +FAT,Fatigue Scale,60-74,M,269,23.5,5.2 +IRR,Irritability Scale,18-29,F,717,18.7,5.6 +IRR,Irritability Scale,45-59,M,410,21.9,4.6 +IRR,Irritability Scale,18-29,M,887,16.3,6.0 +IRR,Irritability Scale,60-74,M,898,14.9,7.4 +IRR,Irritability Scale,45-59,F,704,16.3,5.9 +FAT,Fatigue Scale,18-29,F,330,21.3,5.0 +WDR,Withdrawal Scale,45-59,F,878,22.8,6.6 +IRR,Irritability Scale,60-74,F,764,18.1,7.2 +FAT,Fatigue Scale,60-74,F,606,15.5,7.4 +WDR,Withdrawal Scale,45-59,M,331,19.2,8.4 diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0032/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-t0032/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0032/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-t0032/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0032/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-t0032/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0032/task.toml b/tasks/psychometrics/psychometrics-norms-d3-t0032/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3210773f05301ee227fd4d945b84ea417ab8b655 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-t0032/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-t0032/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..18887332893ae7436b76f7f16e7ecfd4f8a4e34c --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0032/tests/checks.json @@ -0,0 +1,260 @@ +[ + { + "path": "clients.C262.age", + "type": "int", + "value": 58, + "weight": 1.0 + }, + { + "path": "clients.C262.scales.FAT.z", + "type": "number", + "value": 0.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C262.scales.FAT.t_score", + "type": "number", + "value": 51.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C262.scales.FAT.percentile", + "type": "number", + "value": 57.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C262.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C262.scales.WDR.z", + "type": "number", + "value": 1.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C262.scales.WDR.t_score", + "type": "number", + "value": 65.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C262.scales.WDR.percentile", + "type": "number", + "value": 93.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C262.scales.WDR.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C350.age", + "type": "int", + "value": 46, + "weight": 1.0 + }, + { + "path": "clients.C350.scales.FAT.z", + "type": "number", + "value": -1.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C350.scales.FAT.t_score", + "type": "number", + "value": 32.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C350.scales.FAT.percentile", + "type": "number", + "value": 3.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C350.scales.FAT.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C350.scales.WDR.z", + "type": "number", + "value": -0.38, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C350.scales.WDR.t_score", + "type": "number", + "value": 46.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C350.scales.WDR.percentile", + "type": "number", + "value": 35.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C350.scales.WDR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C349.age", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C349.scales.FAT.z", + "type": "number", + "value": 0.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C349.scales.FAT.t_score", + "type": "number", + "value": 53.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C349.scales.FAT.percentile", + "type": "number", + "value": 65.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C349.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C349.scales.WDR.z", + "type": "number", + "value": -0.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C349.scales.WDR.t_score", + "type": "number", + "value": 45.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C349.scales.WDR.percentile", + "type": "number", + "value": 31.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C349.scales.WDR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C234.age", + "type": "int", + "value": 47, + "weight": 1.0 + }, + { + "path": "clients.C234.scales.FAT.z", + "type": "number", + "value": 0.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C234.scales.FAT.t_score", + "type": "number", + "value": 57.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C234.scales.FAT.percentile", + "type": "number", + "value": 78.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C234.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C234.scales.WDR.z", + "type": "number", + "value": -1.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C234.scales.WDR.t_score", + "type": "number", + "value": 39.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C234.scales.WDR.percentile", + "type": "number", + "value": 15.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C234.scales.WDR.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C179" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [ + "C262:WDR" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0032/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-t0032/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0032/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-t0032/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0044/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..d795f415aee0583daf83ef3935c0742e16c7a8a5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C397,F,1952-01-07,2025-02-02,IRR,21,self +C363,M,1982-02-10,2025-03-21,ATT,34,occupational health +C325,F,1980-07-18,2025-07-16,IRR,22,self +C363,M,1982-02-10,2025-03-21,IRR,22,self +C313,F,1949-06-17,2025-03-05,ATT,25,self +C313,F,1949-06-17,2025-03-05,IRR,6,occupational health +C191,F,1963-03-02,2025-10-19,IRR,20,occupational health +C191,F,1963-03-02,2025-10-19,ATT,23,GP +C397,F,1952-01-07,2025-02-02,ATT,26,occupational health +C325,F,1980-07-18,2025-07-16,ATT,41,GP diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..5a36b5695ebae4e769586c1b659db83119533cd1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +IRR,Irritability Scale,30-44,M,313,13.9,6.0 +IRR,Irritability Scale,60-74,F,324,13.2,6.5 +ATT,Attention Difficulties Scale,30-44,F,332,25.3,8.0 +IRR,Irritability Scale,45-59,M,154,16.6,7.5 +WDR,Withdrawal Scale,60-74,M,561,22.8,7.5 +IRR,Irritability Scale,30-44,F,706,13.4,6.9 +ATT,Attention Difficulties Scale,18-29,F,207,26.8,5.0 +ATT,Attention Difficulties Scale,45-59,M,520,22.2,8.0 +IRR,Irritability Scale,45-59,F,333,17.1,6.9 +ATT,Attention Difficulties Scale,60-74,M,491,23.0,5.0 +WDR,Withdrawal Scale,45-59,F,225,20.9,6.3 +IRR,Irritability Scale,60-74,M,348,18.6,6.9 +IRR,Irritability Scale,18-29,F,396,15.2,5.9 +WDR,Withdrawal Scale,18-29,F,568,23.5,6.8 +ATT,Attention Difficulties Scale,60-74,F,170,24.6,5.1 +ATT,Attention Difficulties Scale,45-59,F,246,24.2,6.7 +ATT,Attention Difficulties Scale,18-29,M,736,25.1,6.1 +ATT,Attention Difficulties Scale,30-44,M,464,26.2,6.8 +WDR,Withdrawal Scale,30-44,F,425,22.6,7.0 +WDR,Withdrawal Scale,30-44,M,773,18.3,7.4 +IRR,Irritability Scale,18-29,M,232,15.4,4.3 +WDR,Withdrawal Scale,60-74,F,344,20.4,7.7 +WDR,Withdrawal Scale,18-29,M,486,20.1,6.7 +WDR,Withdrawal Scale,45-59,M,783,18.7,7.5 diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0044/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-t0044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0044/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-t0044/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0044/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-t0044/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0044/task.toml b/tasks/psychometrics/psychometrics-norms-d3-t0044/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d51ab6404ed20e0ad6c3dfcc368742c0f89ec583 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-t0044/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-t0044/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4649d7b11c7849c8e9a38e129a2c819fe4a7a4e9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0044/tests/checks.json @@ -0,0 +1,265 @@ +[ + { + "path": "clients.C325.age", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C325.scales.IRR.z", + "type": "number", + "value": 1.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C325.scales.IRR.t_score", + "type": "number", + "value": 62.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C325.scales.IRR.percentile", + "type": "number", + "value": 89.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C325.scales.IRR.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C325.scales.ATT.z", + "type": "number", + "value": 1.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C325.scales.ATT.t_score", + "type": "number", + "value": 69.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C325.scales.ATT.percentile", + "type": "number", + "value": 97.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C325.scales.ATT.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C363.age", + "type": "int", + "value": 43, + "weight": 1.0 + }, + { + "path": "clients.C363.scales.IRR.z", + "type": "number", + "value": 1.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C363.scales.IRR.t_score", + "type": "number", + "value": 63.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C363.scales.IRR.percentile", + "type": "number", + "value": 91.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C363.scales.IRR.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C363.scales.ATT.z", + "type": "number", + "value": 1.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C363.scales.ATT.t_score", + "type": "number", + "value": 61.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C363.scales.ATT.percentile", + "type": "number", + "value": 87.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C363.scales.ATT.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C397.age", + "type": "int", + "value": 73, + "weight": 1.0 + }, + { + "path": "clients.C397.scales.IRR.z", + "type": "number", + "value": 1.2, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C397.scales.IRR.t_score", + "type": "number", + "value": 62.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C397.scales.IRR.percentile", + "type": "number", + "value": 88.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C397.scales.IRR.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C397.scales.ATT.z", + "type": "number", + "value": 0.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C397.scales.ATT.t_score", + "type": "number", + "value": 52.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C397.scales.ATT.percentile", + "type": "number", + "value": 60.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C397.scales.ATT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C191.age", + "type": "int", + "value": 62, + "weight": 1.0 + }, + { + "path": "clients.C191.scales.IRR.z", + "type": "number", + "value": 1.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C191.scales.IRR.t_score", + "type": "number", + "value": 60.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C191.scales.IRR.percentile", + "type": "number", + "value": 85.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C191.scales.IRR.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C191.scales.ATT.z", + "type": "number", + "value": -0.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C191.scales.ATT.t_score", + "type": "number", + "value": 46.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C191.scales.ATT.percentile", + "type": "number", + "value": 37.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C191.scales.ATT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C313" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [ + "C191:IRR", + "C325:ATT", + "C325:IRR", + "C363:ATT", + "C363:IRR", + "C397:IRR" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0044/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-t0044/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0044/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-t0044/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0056/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..219f046733cc27f10349de1c5d633a5381038edf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C206,F,1995-11-07,2025-11-04,ATT,29,self +C227,M,2006-09-01,2025-07-15,ATT,36,GP +C317,M,1965-07-21,2025-09-24,ATT,33,occupational health +C206,F,1995-11-07,2025-11-04,IRR,24,self +C317,M,1965-07-21,2025-09-24,IRR,51,occupational health +C227,M,2006-09-01,2025-07-15,IRR,21,GP +C180,M,1948-11-13,2025-03-07,ATT,28,self +C181,F,1995-07-18,2025-11-21,IRR,31,self +C180,M,1948-11-13,2025-03-07,IRR,34,occupational health +C181,F,1995-07-18,2025-11-21,ATT,48,self diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..3fbe233ff22820a564dc61608cb9dd4ceebcf80d --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +WDR,Withdrawal Scale,30-44,F,813,19.0,8.5 +ATT,Attention Difficulties Scale,18-29,M,284,29.4,5.0 +IRR,Irritability Scale,45-59,M,793,32.0,6.9 +ATT,Attention Difficulties Scale,18-29,F,332,29.7,6.2 +WDR,Withdrawal Scale,60-74,M,347,22.3,6.4 +ATT,Attention Difficulties Scale,45-59,F,720,28.6,4.4 +WDR,Withdrawal Scale,45-59,M,458,19.9,4.5 +IRR,Irritability Scale,60-74,F,169,32.8,7.2 +IRR,Irritability Scale,30-44,M,828,26.3,7.0 +ATT,Attention Difficulties Scale,30-44,F,354,31.7,6.3 +WDR,Withdrawal Scale,18-29,M,233,15.9,5.5 +IRR,Irritability Scale,30-44,F,408,26.8,5.6 +WDR,Withdrawal Scale,45-59,F,822,19.5,5.5 +WDR,Withdrawal Scale,30-44,M,312,19.6,7.0 +ATT,Attention Difficulties Scale,30-44,M,801,28.7,5.9 +ATT,Attention Difficulties Scale,60-74,F,283,25.6,7.7 +IRR,Irritability Scale,18-29,F,817,27.5,6.5 +ATT,Attention Difficulties Scale,60-74,M,270,24.9,4.4 +WDR,Withdrawal Scale,60-74,F,769,13.5,8.2 +IRR,Irritability Scale,60-74,M,389,32.7,8.1 +ATT,Attention Difficulties Scale,45-59,M,325,24.6,4.3 +IRR,Irritability Scale,18-29,M,293,28.3,5.1 +WDR,Withdrawal Scale,18-29,F,508,19.3,6.1 +IRR,Irritability Scale,45-59,F,366,32.8,8.2 diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0056/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-t0056/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0056/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-t0056/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0056/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-t0056/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0056/task.toml b/tasks/psychometrics/psychometrics-norms-d3-t0056/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..45bce36492c1c3142ea4e191db827f61d4ea492e --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-t0056/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-t0056/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f61d0e669348c83a80b263a511d1b11420052b08 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0056/tests/checks.json @@ -0,0 +1,263 @@ +[ + { + "path": "clients.C317.age", + "type": "int", + "value": 60, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.IRR.z", + "type": "number", + "value": 2.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.IRR.t_score", + "type": "number", + "value": 72.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.IRR.percentile", + "type": "number", + "value": 98.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.IRR.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C317.scales.ATT.z", + "type": "number", + "value": 1.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.ATT.t_score", + "type": "number", + "value": 68.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.ATT.percentile", + "type": "number", + "value": 96.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C317.scales.ATT.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C206.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C206.scales.IRR.z", + "type": "number", + "value": -0.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C206.scales.IRR.t_score", + "type": "number", + "value": 44.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C206.scales.IRR.percentile", + "type": "number", + "value": 29.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C206.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C206.scales.ATT.z", + "type": "number", + "value": -0.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C206.scales.ATT.t_score", + "type": "number", + "value": 48.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C206.scales.ATT.percentile", + "type": "number", + "value": 45.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C206.scales.ATT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C227.age", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C227.scales.IRR.z", + "type": "number", + "value": -1.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C227.scales.IRR.t_score", + "type": "number", + "value": 35.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C227.scales.IRR.percentile", + "type": "number", + "value": 7.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C227.scales.IRR.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C227.scales.ATT.z", + "type": "number", + "value": 1.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C227.scales.ATT.t_score", + "type": "number", + "value": 63.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C227.scales.ATT.percentile", + "type": "number", + "value": 90.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C227.scales.ATT.range", + "type": "str", + "value": "high", + "weight": 1.0 + }, + { + "path": "clients.C181.age", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "clients.C181.scales.IRR.z", + "type": "number", + "value": 0.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C181.scales.IRR.t_score", + "type": "number", + "value": 57.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C181.scales.IRR.percentile", + "type": "number", + "value": 77.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C181.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C181.scales.ATT.z", + "type": "number", + "value": 2.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C181.scales.ATT.t_score", + "type": "number", + "value": 75.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C181.scales.ATT.percentile", + "type": "number", + "value": 99.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C181.scales.ATT.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C180" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [ + "C181:ATT", + "C227:ATT", + "C317:ATT", + "C317:IRR" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0056/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-t0056/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0056/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-t0056/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0068/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..71a4cd868456a28eb1dc779461bee25878920411 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C264,M,2005-07-24,2025-10-02,WDR,25,GP +C103,F,1965-06-17,2025-06-14,IRR,27,occupational health +C242,M,2007-05-16,2025-05-08,WDR,14,GP +C360,F,1996-06-18,2025-09-12,WDR,6,occupational health +C170,F,1993-09-12,2025-05-26,IRR,20,self +C242,M,2007-05-16,2025-05-08,IRR,39,GP +C103,F,1965-06-17,2025-06-14,WDR,19,self +C170,F,1993-09-12,2025-05-26,WDR,19,self +C360,F,1996-06-18,2025-09-12,IRR,31,self +C264,M,2005-07-24,2025-10-02,IRR,39,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..665c4324679e85df5350e1077a71a89a059281f3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +ATT,Attention Difficulties Scale,45-59,F,527,33.5,6.0 +WDR,Withdrawal Scale,45-59,M,709,15.8,4.6 +ATT,Attention Difficulties Scale,30-44,M,285,26.7,7.9 +WDR,Withdrawal Scale,18-29,M,139,18.9,7.1 +WDR,Withdrawal Scale,60-74,F,845,14.7,7.0 +WDR,Withdrawal Scale,30-44,M,767,15.6,8.2 +IRR,Irritability Scale,45-59,M,278,21.7,4.5 +IRR,Irritability Scale,60-74,M,554,31.2,4.6 +ATT,Attention Difficulties Scale,18-29,M,688,31.0,8.0 +WDR,Withdrawal Scale,60-74,M,145,14.1,5.7 +WDR,Withdrawal Scale,18-29,F,385,17.7,8.2 +ATT,Attention Difficulties Scale,60-74,F,480,26.4,6.4 +IRR,Irritability Scale,45-59,F,276,28.6,5.2 +ATT,Attention Difficulties Scale,60-74,M,254,31.5,4.2 +IRR,Irritability Scale,18-29,M,221,25.5,5.3 +ATT,Attention Difficulties Scale,18-29,F,528,32.1,5.2 +IRR,Irritability Scale,30-44,M,373,26.8,5.0 +WDR,Withdrawal Scale,45-59,F,649,16.4,5.7 +IRR,Irritability Scale,30-44,F,349,29.1,5.0 +ATT,Attention Difficulties Scale,30-44,F,257,29.8,8.5 +IRR,Irritability Scale,60-74,F,521,28.7,6.3 +IRR,Irritability Scale,18-29,F,191,27.7,4.3 +WDR,Withdrawal Scale,30-44,F,684,16.5,6.4 +ATT,Attention Difficulties Scale,45-59,M,279,25.6,8.4 diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0068/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-t0068/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0068/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-t0068/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0068/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-t0068/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0068/task.toml b/tasks/psychometrics/psychometrics-norms-d3-t0068/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..54f9450cb83695d9c8f74212b3459d9ae587cb25 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-t0068/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-t0068/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..43e3de8a88da402072e1fbd4c4e9f0092ef4715f --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0068/tests/checks.json @@ -0,0 +1,260 @@ +[ + { + "path": "clients.C264.age", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "clients.C264.scales.WDR.z", + "type": "number", + "value": 0.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C264.scales.WDR.t_score", + "type": "number", + "value": 58.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C264.scales.WDR.percentile", + "type": "number", + "value": 80.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C264.scales.WDR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C264.scales.IRR.z", + "type": "number", + "value": 2.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C264.scales.IRR.t_score", + "type": "number", + "value": 75.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C264.scales.IRR.percentile", + "type": "number", + "value": 99.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C264.scales.IRR.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C103.age", + "type": "int", + "value": 59, + "weight": 1.0 + }, + { + "path": "clients.C103.scales.WDR.z", + "type": "number", + "value": 0.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C103.scales.WDR.t_score", + "type": "number", + "value": 54.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C103.scales.WDR.percentile", + "type": "number", + "value": 67.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C103.scales.WDR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C103.scales.IRR.z", + "type": "number", + "value": -0.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C103.scales.IRR.t_score", + "type": "number", + "value": 46.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C103.scales.IRR.percentile", + "type": "number", + "value": 37.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C103.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C170.age", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "clients.C170.scales.WDR.z", + "type": "number", + "value": 0.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C170.scales.WDR.t_score", + "type": "number", + "value": 53.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C170.scales.WDR.percentile", + "type": "number", + "value": 65.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C170.scales.WDR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C170.scales.IRR.z", + "type": "number", + "value": -1.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C170.scales.IRR.t_score", + "type": "number", + "value": 31.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C170.scales.IRR.percentile", + "type": "number", + "value": 3.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C170.scales.IRR.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C360.age", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C360.scales.WDR.z", + "type": "number", + "value": -1.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C360.scales.WDR.t_score", + "type": "number", + "value": 35.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C360.scales.WDR.percentile", + "type": "number", + "value": 7.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C360.scales.WDR.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C360.scales.IRR.z", + "type": "number", + "value": 0.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C360.scales.IRR.t_score", + "type": "number", + "value": 57.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C360.scales.IRR.percentile", + "type": "number", + "value": 77.9, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C360.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C242" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [ + "C264:IRR" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0068/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-t0068/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0068/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-t0068/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0080/environment/Dockerfile b/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/clients.csv b/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/clients.csv new file mode 100644 index 0000000000000000000000000000000000000000..e56f6a3c8da07c7516947071194f599418036d4b --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/clients.csv @@ -0,0 +1,11 @@ +client_id,sex,date_of_birth,test_date,scale,raw_score,referral +C113,M,1987-04-23,2025-03-03,FAT,26,GP +C217,M,1965-02-06,2025-02-03,FAT,5,occupational health +C394,F,1973-06-06,2025-05-07,FAT,17,GP +C306,M,1994-04-17,2025-08-16,FAT,25,occupational health +C394,F,1973-06-06,2025-05-07,IRR,40,GP +C113,M,1987-04-23,2025-03-03,IRR,27,occupational health +C217,M,1965-02-06,2025-02-03,IRR,16,occupational health +C306,M,1994-04-17,2025-08-16,IRR,42,occupational health +C102,F,1945-11-03,2025-07-11,FAT,26,GP +C102,F,1945-11-03,2025-07-11,IRR,24,occupational health diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/norms.csv b/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/norms.csv new file mode 100644 index 0000000000000000000000000000000000000000..e31b95c21ecb4d3e119a03c0fcfe77daee6d7768 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/norms.csv @@ -0,0 +1,25 @@ +scale,scale_name,age_band,sex,n,mean,sd +FAT,Fatigue Scale,45-59,F,281,17.1,4.6 +IRR,Irritability Scale,30-44,M,626,26.7,7.3 +IRR,Irritability Scale,45-59,F,540,26.9,6.3 +FAT,Fatigue Scale,60-74,M,402,15.7,6.9 +ATT,Attention Difficulties Scale,45-59,F,271,34.6,7.2 +IRR,Irritability Scale,30-44,F,204,27.3,8.3 +IRR,Irritability Scale,45-59,M,364,20.4,5.7 +ATT,Attention Difficulties Scale,60-74,M,886,35.9,5.3 +FAT,Fatigue Scale,18-29,F,815,19.9,4.2 +ATT,Attention Difficulties Scale,60-74,F,120,34.7,5.2 +ATT,Attention Difficulties Scale,30-44,F,288,33.6,4.6 +FAT,Fatigue Scale,30-44,F,239,19.8,8.4 +IRR,Irritability Scale,60-74,F,853,20.8,6.3 +IRR,Irritability Scale,60-74,M,199,24.8,7.5 +ATT,Attention Difficulties Scale,18-29,F,189,32.6,6.7 +ATT,Attention Difficulties Scale,30-44,M,450,30.0,5.9 +ATT,Attention Difficulties Scale,45-59,M,618,27.8,4.3 +FAT,Fatigue Scale,45-59,M,845,17.6,7.8 +FAT,Fatigue Scale,18-29,M,796,19.2,8.4 +IRR,Irritability Scale,18-29,F,858,26.2,8.0 +IRR,Irritability Scale,18-29,M,687,24.5,7.6 +FAT,Fatigue Scale,60-74,F,241,17.0,4.2 +FAT,Fatigue Scale,30-44,M,630,20.4,6.8 +ATT,Attention Difficulties Scale,18-29,M,120,28.6,4.4 diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/norms_guide.md b/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/norms_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b9487b87357ae4212b222e4dccbdc9c0328af011 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/environment/workdir/norms_guide.md @@ -0,0 +1,26 @@ +# Using the norm table + +The scales and norms are invented for practice. + +`norms.csv` gives the mean and standard deviation (SD) of the raw score in each norm group. A norm group is a scale, an age band and a sex. The age bands are inclusive: `30-44` covers ages 30 to 44. + +Age is the client's age in completed years on the test date (the number of birthdays the client has had by that date, counting a birthday on the test date itself). A client whose age falls outside every age band has no norm group and cannot be converted. + +For a client with raw score `x` in a norm group with mean `M` and standard deviation `SD`: + + z = (x - M) / SD + T score = 50 + 10 * z + percentile = 100 * Phi(z), Phi(z) = 0.5 * (1 + erf(z / sqrt(2))) + +`erf` is the error function (`math.erf` in Python). Use the unrounded z in the T score and the percentile. + +## Ranges + +Classify the unrounded T score: + +| Range | T score | +|---|---| +| `very-high` | 70 or more | +| `high` | 60 or more, but under 70 | +| `average` | 40 or more, but under 60 | +| `low` | under 40 | diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0080/instruction.md b/tasks/psychometrics/psychometrics-norms-d3-t0080/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ac65fd01d946cdd100af282b3e886708b621cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/instruction.md @@ -0,0 +1,19 @@ +# Norm-referenced scores + +`clients.csv` holds raw scores on 2 scales (one row per client and scale). `norms.csv` is the norm table and `norms_guide.md` says how to use it. The norm table also lists a scale that nobody here took. + +Convert every raw score using the norm group that matches the client's scale, age and sex. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id, for every client who has a norm group. Each value has + - `age`: age in completed years on the test date, an integer. + - `scales`: an object keyed by scale code, each with + - `z`: the z score, 2 decimals. + - `t_score`: the T score, 1 decimal. + - `percentile`: the percentile rank, 1 decimal. + - `range`: one of `very-high`, `high`, `average`, `low`. +- `no_norm_group`: list of the client ids whose age is outside every age band (any order). Give no scores for them. +- `high_or_above`: list of strings of the form `":"` for every score in the `high` or `very-high` range (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0080/solution/oracle.py b/tasks/psychometrics/psychometrics-norms-d3-t0080/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0080/solution/solve.sh b/tasks/psychometrics/psychometrics-norms-d3-t0080/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0080/task.toml b/tasks/psychometrics/psychometrics-norms-d3-t0080/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e6f3c8a566538d862ad0666fc0a4f3aa29333120 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "norms", "isced-0313", "train"] +isced_f = "0313" +family = "norms" +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/psychometrics/psychometrics-norms-d3-t0080/tests/checks.json b/tasks/psychometrics/psychometrics-norms-d3-t0080/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8897fd705b78c46e6247a83de7e8e22f90d1de15 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-d3-t0080/tests/checks.json @@ -0,0 +1,261 @@ +[ + { + "path": "clients.C306.age", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "clients.C306.scales.FAT.z", + "type": "number", + "value": 0.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C306.scales.FAT.t_score", + "type": "number", + "value": 56.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C306.scales.FAT.percentile", + "type": "number", + "value": 75.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C306.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C306.scales.IRR.z", + "type": "number", + "value": 2.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C306.scales.IRR.t_score", + "type": "number", + "value": 71.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C306.scales.IRR.percentile", + "type": "number", + "value": 98.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C306.scales.IRR.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C394.age", + "type": "int", + "value": 51, + "weight": 1.0 + }, + { + "path": "clients.C394.scales.FAT.z", + "type": "number", + "value": -0.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C394.scales.FAT.t_score", + "type": "number", + "value": 49.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C394.scales.FAT.percentile", + "type": "number", + "value": 49.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C394.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C394.scales.IRR.z", + "type": "number", + "value": 2.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C394.scales.IRR.t_score", + "type": "number", + "value": 70.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C394.scales.IRR.percentile", + "type": "number", + "value": 98.1, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C394.scales.IRR.range", + "type": "str", + "value": "very-high", + "weight": 1.0 + }, + { + "path": "clients.C217.age", + "type": "int", + "value": 59, + "weight": 1.0 + }, + { + "path": "clients.C217.scales.FAT.z", + "type": "number", + "value": -1.62, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C217.scales.FAT.t_score", + "type": "number", + "value": 33.8, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C217.scales.FAT.percentile", + "type": "number", + "value": 5.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C217.scales.FAT.range", + "type": "str", + "value": "low", + "weight": 1.0 + }, + { + "path": "clients.C217.scales.IRR.z", + "type": "number", + "value": -0.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C217.scales.IRR.t_score", + "type": "number", + "value": 42.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C217.scales.IRR.percentile", + "type": "number", + "value": 22.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C217.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C113.age", + "type": "int", + "value": 37, + "weight": 1.0 + }, + { + "path": "clients.C113.scales.FAT.z", + "type": "number", + "value": 0.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C113.scales.FAT.t_score", + "type": "number", + "value": 58.2, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C113.scales.FAT.percentile", + "type": "number", + "value": 79.5, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C113.scales.FAT.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "clients.C113.scales.IRR.z", + "type": "number", + "value": 0.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "clients.C113.scales.IRR.t_score", + "type": "number", + "value": 50.4, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C113.scales.IRR.percentile", + "type": "number", + "value": 51.6, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "clients.C113.scales.IRR.range", + "type": "str", + "value": "average", + "weight": 1.0 + }, + { + "path": "no_norm_group", + "type": "set", + "value": [ + "C102" + ], + "item": "str", + "weight": 2 + }, + { + "path": "high_or_above", + "type": "set", + "value": [ + "C306:IRR", + "C394:IRR" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-norms-d3-t0080/tests/test.sh b/tasks/psychometrics/psychometrics-norms-d3-t0080/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-norms-d3-t0080/tests/verify.py b/tasks/psychometrics/psychometrics-norms-d3-t0080/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-norms-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/psychometrics/psychometrics-reliability-d1-e0001/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-e0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0001/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-e0001/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..c663b4b66c1200729f0f0bd4b8b1a99865a60351 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0001/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R446,south,4,3,3,3,3 +R479,east,3,4,3,2,4 +R432,east,5,3,4,5,4 +R053,south,1,1,2,2,1 +R085,north,4,3,4,3,3 +R203,east,4,3,5,3,3 +R059,north,3,2,2,3,4 +R079,south,4,4,3,5,3 +R170,east,1,1,1,3,1 +R255,east,4,5,3,5,3 +R249,east,5,4,3,4,4 +R360,south,3,3,2,4,4 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0001/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-e0001/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0001/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0001/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-e0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0b5176e7d7f85e16137a0586da8f4a8ddfe9d965 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0001/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Work Engagement Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0001/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-e0001/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0001/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0001/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-e0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0001/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0001/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-e0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8831f64079e9c9372bbb4e85698e34af40190b52 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "eval"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-e0001/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-e0001/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1fc077cf35cb1f8ed3a548216e0cc9012b38a461 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0001/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 3.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 1.72, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 3.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.455, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 2.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.174, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 3.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.182, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 3.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.174, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 21.538, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.861, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0001/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-e0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-e0001/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-e0001/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-e0013/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-e0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0013/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-e0013/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..c0ba4867086887179ba6abc64ed2c0a3d112a866 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0013/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R198,north,4,4,3,4,2 +R180,east,3,2,2,2,4 +R260,east,5,4,4,5,2 +R464,south,3,3,3,3,4 +R244,south,3,4,2,3,2 +R231,north,3,3,3,4,2 +R290,south,4,4,5,4,5 +R219,east,3,2,4,2,2 +R077,north,5,3,4,3,4 +R012,south,2,3,3,2,2 +R074,east,3,2,2,2,1 +R306,south,5,3,4,5,4 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0013/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-e0013/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0013/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0013/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-e0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14ddf354e74c7cf37b798d43ab8490adb1b0dcff --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0013/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0013/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-e0013/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0013/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0013/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-e0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0013/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0013/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-e0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5b746cdf348b6bbf63a5d30eaa19347f97b2179a --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "eval"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-e0013/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-e0013/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..69fbbc7578d71cdb21e576e225eaec688a004ec4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-e0013/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 3.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 0.992, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 3.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.629, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 3.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.932, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 3.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.295, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 2.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.606, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 14.727, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.787, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-e0013/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-e0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-e0013/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-e0013/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0001/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-t0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0001/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-t0001/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..6a973811f9ddbc3e8bff539ddcba8b12be6288df --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0001/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R202,south,3,3,3,3,3 +R294,north,1,2,1,2,2 +R006,south,4,3,4,4,2 +R426,east,1,3,3,2,3 +R334,south,3,2,1,5,4 +R218,north,2,3,3,3,4 +R298,east,1,1,2,3,2 +R122,east,4,4,4,3,4 +R424,north,4,4,3,5,5 +R370,south,2,4,1,3,3 +R439,east,4,3,3,2,3 +R359,south,2,3,3,2,4 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0001/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-t0001/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0001/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0001/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-t0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..08cba1e8c3a7c604a504d94e0b7180f6a8d93c2e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0001/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Study Motivation Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0001/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-t0001/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0001/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0001/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0001/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0001/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-t0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..05053ba65309e79be5ed8ec22da26b816cb0fd01 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-t0001/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-t0001/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b97ef6c9530d3da013d4ae015773eabbe1f00623 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0001/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 2.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 1.538, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 2.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.811, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 2.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.174, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 3.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.174, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 3.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 0.932, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 13.72, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.737, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0001/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0001/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-t0001/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0013/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-t0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0013/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-t0013/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..6667184562b60aa52d9a84e8e39283fe63c48f9e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0013/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R399,north,2,1,2,1,1 +R453,north,4,2,3,2,3 +R285,east,5,5,5,5,4 +R440,south,4,3,3,2,2 +R002,east,4,4,4,4,4 +R232,east,2,5,5,2,1 +R287,east,3,4,4,3,3 +R322,north,3,2,1,1,1 +R407,north,3,3,2,2,4 +R309,north,2,3,2,3,2 +R220,south,3,2,2,2,3 +R154,east,3,2,1,4,3 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0013/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-t0013/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0013/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0013/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-t0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f52b870522b0bc212cee0c0de9b026ec5823ffaf --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0013/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Social Confidence Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0013/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-t0013/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0013/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0013/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0013/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0013/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-t0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d3371f526700ecb230d1a70d43c3ecf7ff436c1c --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-t0013/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-t0013/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b72bae79df1c709cb0afb7f0a6d2730bdaccf2d9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0013/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 3.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 0.879, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 3.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.636, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 2.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.97, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 2.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.538, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 2.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.356, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 21.788, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.827, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0013/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0013/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-t0013/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0025/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-t0025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0025/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0025/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-t0025/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..ae7b3c41d4f2633091cf0896c603655b5abb0db4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0025/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R202,south,2,2,2,3,4 +R235,east,2,2,4,4,3 +R486,north,3,4,3,2,4 +R440,south,3,3,4,3,3 +R470,east,2,2,2,3,1 +R350,east,4,4,4,4,4 +R104,south,4,3,5,3,4 +R147,north,1,2,1,2,1 +R489,south,2,3,3,3,2 +R298,north,2,4,4,4,5 +R182,east,4,2,4,2,4 +R467,south,2,3,3,2,3 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0025/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-t0025/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0025/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0025/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-t0025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0b5176e7d7f85e16137a0586da8f4a8ddfe9d965 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0025/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Work Engagement Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0025/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-t0025/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0025/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0025/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0025/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0025/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0025/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-t0025/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f168c460e583239c9b1afc84484ee38d2e3c0b40 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0025/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-t0025/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-t0025/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..26fb013d41d6c31306bcdfbeeccbee45efa3f942 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0025/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 2.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 0.992, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 2.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.697, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 3.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.295, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 2.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 0.629, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 3.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.606, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 14.568, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.802, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0025/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0025/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-t0025/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0037/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-t0037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0037/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0037/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-t0037/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..b3a80d2b85c0e1e9159eb42f7e752e0f50cf3c49 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0037/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R235,south,3,3,3,3,3 +R018,north,2,4,2,4,5 +R392,south,2,3,4,3,4 +R014,south,3,4,3,3,4 +R249,east,3,2,3,4,3 +R277,north,2,2,2,2,3 +R059,east,3,1,4,2,3 +R001,east,4,3,3,3,4 +R195,north,3,3,1,3,2 +R368,east,1,1,2,1,1 +R472,east,1,2,1,2,1 +R262,south,3,2,3,2,3 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0037/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-t0037/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0037/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0037/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-t0037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14ddf354e74c7cf37b798d43ab8490adb1b0dcff --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0037/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0037/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-t0037/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0037/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0037/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0037/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0037/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0037/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-t0037/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d73ad301a39d8ed3d949a42eb0d59300cf126617 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0037/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-t0037/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-t0037/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..da44fdcd67047c1571f25fec0487611f3ef382c2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0037/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 2.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 0.818, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 2.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.0, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 2.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.992, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 2.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 0.788, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 3.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.455, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 14.023, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.8, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0037/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0037/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0037/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-t0037/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0049/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-t0049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0049/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0049/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-t0049/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..98276c6021304a4ba1a5aa86122278c95e087662 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0049/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R046,north,4,4,5,3,4 +R093,east,3,3,2,5,3 +R435,north,2,3,2,3,1 +R260,east,4,3,4,3,3 +R172,north,4,3,3,4,3 +R123,north,3,2,4,3,5 +R262,south,2,3,2,2,3 +R121,north,2,2,3,2,3 +R486,north,4,3,2,5,3 +R342,east,3,3,3,2,1 +R132,south,2,1,1,2,2 +R399,east,4,4,3,3,4 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0049/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-t0049/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0049/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0049/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-t0049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14ddf354e74c7cf37b798d43ab8490adb1b0dcff --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0049/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0049/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-t0049/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0049/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0049/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0049/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0049/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-t0049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..04de0e591be243935a06b445608c5faf71892ad1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0049/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-t0049/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-t0049/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6338daadfc8b00e44ff34cfba924bc4625827636 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0049/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 3.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 0.811, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 2.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.697, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 2.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.242, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 3.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.174, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 2.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.356, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 12.932, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.74, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0049/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0049/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-t0049/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0061/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-t0061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0061/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0061/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-t0061/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..ae100cd8257e882f1bbd97c199be59642c431e0e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0061/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R183,north,3,4,4,4,3 +R054,south,4,5,4,4,3 +R089,north,3,4,5,5,3 +R485,north,3,3,4,2,5 +R150,north,2,3,1,3,3 +R420,east,2,3,3,2,3 +R388,north,2,3,4,3,4 +R499,south,2,3,2,1,2 +R327,south,1,2,4,3,2 +R037,east,3,2,2,4,3 +R320,east,2,2,1,1,3 +R163,south,5,4,3,5,2 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0061/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-t0061/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0061/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0061/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-t0061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14ddf354e74c7cf37b798d43ab8490adb1b0dcff --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0061/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0061/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-t0061/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0061/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0061/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0061/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0061/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0061/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-t0061/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6b9dc21bcc772cf33ac9aee5ad81e59663a03619 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0061/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-t0061/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-t0061/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6506c3bb0198a6a40fd19a836072d1085137d6c9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0061/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 2.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 1.152, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 3.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.879, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 3.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.72, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 3.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.902, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 3.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 0.727, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 14.909, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.715, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0061/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0061/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0061/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-t0061/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0073/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d1-t0073/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0073/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0073/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d1-t0073/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..465c08b31630fd250542bc5969b2abe9f8fbc45a --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0073/environment/workdir/item_responses.csv @@ -0,0 +1,13 @@ +respondent_id,site,q1,q2,q3,q4,q5 +R136,north,2,5,2,3,3 +R458,south,4,1,2,2,2 +R237,south,3,4,3,2,3 +R007,north,2,2,2,2,2 +R187,east,5,4,5,4,5 +R391,north,3,3,2,3,3 +R064,south,2,4,3,4,3 +R081,east,1,2,1,2,2 +R462,east,2,3,3,3,3 +R288,east,3,3,3,2,2 +R492,south,3,3,2,3,4 +R430,south,4,4,3,3,5 diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0073/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d1-t0073/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fb4dcfd94ef571d092dd2d0f2c043f9df4412272 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0073/environment/workdir/reliability_notes.md @@ -0,0 +1,11 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0073/instruction.md b/tasks/psychometrics/psychometrics-reliability-d1-t0073/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14ddf354e74c7cf37b798d43ab8490adb1b0dcff --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0073/instruction.md @@ -0,0 +1,13 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 12 people to the 5 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q5`). Each value has + - `mean`: the mean of the item, 2 decimals. + - `variance`: the variance of the item scores, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 5-item scale, 3 decimals. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0073/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d1-t0073/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0073/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0073/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0073/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0073/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0073/task.toml b/tasks/psychometrics/psychometrics-reliability-d1-t0073/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..156422347ee7a752429a61902840104dcffa83ac --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0073/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d1-t0073/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d1-t0073/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5c984046dd8cdfabd716c005b12016f0c95ca423 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d1-t0073/tests/checks.json @@ -0,0 +1,86 @@ +[ + { + "path": "items.q1.mean", + "type": "number", + "value": 2.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q1.variance", + "type": "number", + "value": 1.242, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.mean", + "type": "number", + "value": 3.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.242, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.mean", + "type": "number", + "value": 2.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.992, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.mean", + "type": "number", + "value": 2.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 0.568, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.mean", + "type": "number", + "value": 3.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.174, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 15.72, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.835, + "abs_tol": 0.001, + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d1-t0073/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d1-t0073/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d1-t0073/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d1-t0073/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-e0005/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-e0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0005/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-e0005/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..9352d337d70e99ebd6ef2abc026a673668a356b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0005/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R397,north,2,2,3,3,3,3,2 +R323,south,2,2,2,3,3,4,4 +R489,north,4,3,4,4,5,3,4 +R055,south,2,3,2,3,3,2,5 +R391,north,2,4,3,5,3,2,3 +R237,south,3,4,4,2,3,4,2 +R407,east,2,1,2,4,2,4,2 +R291,north,2,4,3,5,3,2,3 +R344,east,3,3,3,1,4,3,2 +R268,east,2,1,1,4,2,1,1 +R059,north,5,5,5,3,5,4,4 +R168,south,3,2,2,4,2,2,3 +R327,east,5,5,5,1,5,3,3 +R439,south,3,1,1,3,3,1,4 +R496,south,2,4,3,3,3,5,4 +R171,south,5,5,5,1,5,5,3 +R241,east,4,4,3,4,4,3,2 +R118,south,1,1,2,5,2,2,4 +R202,north,4,5,5,2,5,5,3 +R188,east,4,3,2,3,4,3,3 +R410,north,2,1,1,4,3,3,3 +R431,north,2,2,3,3,3,2,3 +R228,north,2,2,3,3,4,3,1 +R258,north,3,4,2,4,4,1,2 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0005/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-e0005/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..78beecff51588b22b6c0cae99c292b9e1dccec36 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0005/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q4, q7. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0005/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-e0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ba85ab47913cdf002170b91ceed8b850cfe2b9b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0005/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Work Engagement Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0005/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-e0005/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0005/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0005/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-e0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0005/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0005/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-e0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..270df6d9c971aac46da56ef536dce21e231bccf7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "eval"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-e0005/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-e0005/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..836ca3edb9502fdddd0ca43c9aebfd9f0342347d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0005/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.332, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.74, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 2.042, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.724, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.592, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.84, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.389, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.612, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.042, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.795, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.471, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.534, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.036, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": -0.078, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 34.911, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.836, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q7" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0005/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-e0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-e0005/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-e0005/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-e0017/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-e0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0017/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-e0017/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..27ec5acdd28678a85588e0584bbbd6975c0e445f --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0017/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R331,north,4,3,2,3,4,4,3 +R391,south,3,3,3,3,4,2,1 +R436,south,5,4,5,3,5,1,3 +R302,east,4,3,3,2,4,3,3 +R184,south,1,3,2,4,2,4,4 +R393,east,4,4,4,3,3,2,4 +R477,north,3,4,3,3,3,2,1 +R285,north,4,4,3,3,3,1,2 +R453,south,3,5,3,3,3,2,3 +R117,east,2,2,3,2,2,5,3 +R466,north,3,3,2,4,3,3,2 +R241,north,4,3,5,3,4,4,3 +R361,east,3,2,3,3,4,2,4 +R101,east,2,4,4,1,2,3,4 +R292,east,4,3,2,2,3,2,3 +R174,north,3,3,3,4,3,5,4 +R222,south,2,2,3,3,2,5,3 +R204,north,1,2,3,2,2,4,5 +R267,south,3,3,3,3,5,3,3 +R177,east,2,2,3,3,3,4,3 +R247,east,2,3,4,2,5,2,2 +R261,north,3,4,4,3,1,3,3 +R224,north,3,3,3,2,3,4,5 +R468,east,4,2,4,3,3,3,2 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0017/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-e0017/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..dd4b8ef7740f11865c50dea0d334f9a753049197 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0017/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q6, q7. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0017/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-e0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..936067e908d6c50de1e9261d1e84f306cca99001 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0017/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0017/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-e0017/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0017/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0017/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-e0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0017/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0017/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-e0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..667e78092fc1101cbc20b694b9507e127058afe6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "eval"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-e0017/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-e0017/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..16a32e892b73f158eb7c81b068e31f6a751b448c --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-e0017/tests/checks.json @@ -0,0 +1,124 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.043, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.618, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.688, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.404, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.694, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.226, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 0.52, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.044, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.101, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.446, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.433, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.637, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.085, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.397, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 16.145, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.692, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q3", + "q4" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-e0017/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-e0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-e0017/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-e0017/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0005/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-t0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0005/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-t0005/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..7b96aa0c10fc382f3b73b0ccff1f10ab8cf2f380 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0005/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R354,east,4,1,2,4,4,5,2 +R124,north,2,3,3,3,2,3,4 +R050,north,2,4,3,3,4,3,2 +R200,north,3,4,3,3,4,3,4 +R031,east,5,3,5,1,5,1,3 +R283,south,3,4,4,3,4,1,2 +R152,north,2,2,1,5,3,4,3 +R361,north,4,4,5,3,2,2,3 +R440,south,3,3,3,3,2,2,3 +R378,north,3,3,4,4,5,2,3 +R385,east,4,4,4,2,2,3,2 +R226,north,3,3,3,2,3,3,3 +R350,east,3,3,2,4,3,2,5 +R058,north,2,4,5,2,2,5,3 +R057,east,2,1,3,3,2,3,2 +R059,north,3,3,2,3,3,4,4 +R393,north,5,5,5,1,5,2,2 +R024,north,2,2,1,4,3,3,4 +R492,east,1,1,1,4,1,4,3 +R426,east,2,2,2,1,2,5,3 +R151,south,4,2,3,4,5,4,2 +R482,south,5,4,4,2,4,2,3 +R129,east,5,5,5,4,4,2,2 +R333,north,5,4,5,3,3,2,3 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0005/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-t0005/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..10b14f2f433ac954a0ad40a99038d9c7becd01bd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0005/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q4, q6. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0005/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-t0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4ef572bf037a2105ef7b70ec5c1da0190e661dee --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0005/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Social Confidence Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0005/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-t0005/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0005/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0005/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0005/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0005/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-t0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..359ee1b4a4fc59fea3b6d97cefae4316fbaabb26 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-t0005/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-t0005/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..35878f203969ca757b32a2cb9ae7ad2dd8e9c1f2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0005/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.476, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.696, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.384, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.711, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.848, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.732, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.172, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.332, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.389, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.384, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.384, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.588, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 0.688, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": -0.262, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 25.911, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.746, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q7" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0005/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0005/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-t0005/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0017/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-t0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0017/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-t0017/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..5a147e3df2b00e0a5a1b5b65d77c99e4a8a04d63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0017/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R434,north,3,4,4,4,3,3,2 +R045,south,2,3,2,3,3,3,3 +R125,south,3,1,3,3,3,3,4 +R446,east,1,2,1,4,2,3,4 +R170,east,3,2,1,3,3,4,4 +R316,north,4,4,4,5,2,3,2 +R074,north,4,4,4,4,3,2,1 +R391,south,3,3,3,4,3,4,2 +R229,north,4,2,4,3,3,3,2 +R364,north,4,2,4,3,4,3,5 +R295,north,5,5,4,5,4,2,1 +R053,north,3,3,3,3,3,2,4 +R410,north,2,2,3,2,3,2,2 +R172,south,3,4,5,2,3,1,3 +R201,north,1,3,3,2,2,3,5 +R234,east,4,4,4,3,3,3,4 +R047,south,3,2,1,2,1,5,3 +R468,north,2,3,4,3,3,2,1 +R272,south,4,4,4,2,5,2,2 +R317,east,4,5,5,3,3,1,2 +R471,north,1,2,3,3,1,2,4 +R385,south,3,3,2,3,4,3,4 +R176,south,3,3,2,5,3,2,4 +R363,south,2,3,4,3,3,3,2 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0017/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-t0017/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..dd4b8ef7740f11865c50dea0d334f9a753049197 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0017/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q6, q7. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0017/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-t0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..936067e908d6c50de1e9261d1e84f306cca99001 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0017/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0017/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-t0017/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0017/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0017/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0017/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0017/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-t0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..79944fbb617c589af89cd191d060ef9614a5a863 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-t0017/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-t0017/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..db71fbee05199718f16f690fc16b1ddcc64d652b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0017/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.172, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.573, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.085, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.72, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.389, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.642, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 0.868, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.219, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 0.775, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.437, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 0.841, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.444, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.558, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.512, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 23.239, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.781, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q4" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0017/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0017/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-t0017/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0029/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-t0029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0029/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0029/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-t0029/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..22c1ca5e5e3263081cd9f83dd7ca0f698a6dcec1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0029/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R453,east,3,3,2,1,4,2,1 +R258,north,3,2,3,3,4,4,3 +R472,east,4,2,2,3,5,3,2 +R439,north,3,1,3,2,4,2,4 +R365,south,1,2,2,3,3,2,3 +R124,east,3,2,4,3,3,2,3 +R042,east,3,2,3,1,2,4,2 +R342,north,4,4,4,5,1,5,4 +R272,south,3,2,3,3,4,3,4 +R288,south,2,3,3,2,3,3,4 +R121,north,4,3,2,2,3,3,3 +R040,east,4,3,3,3,2,2,4 +R233,north,3,2,3,3,4,4,3 +R208,south,4,5,5,4,1,5,5 +R303,south,4,3,4,4,2,3,2 +R325,south,3,3,3,2,2,3,3 +R382,south,3,3,4,4,1,5,4 +R131,south,2,4,5,3,2,4,4 +R209,south,3,3,3,3,3,3,1 +R345,north,4,1,3,3,5,2,4 +R362,east,4,3,3,1,1,3,4 +R409,east,4,1,2,2,4,1,2 +R243,north,4,2,4,2,5,2,1 +R254,north,3,2,3,1,5,2,3 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0029/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-t0029/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..fbf0475b324fdacd686c8ee4ac405b10bd63ebda --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0029/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q1, q5. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0029/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-t0029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4ef572bf037a2105ef7b70ec5c1da0190e661dee --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0029/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Social Confidence Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0029/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-t0029/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0029/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0029/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0029/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0029/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0029/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-t0029/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7be68f10cedb635fb6f3506b24599c0c9858c437 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0029/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-t0029/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-t0029/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8254ac185608d00d0fd7af664a0458ae384f9fa1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0029/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 0.63, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": -0.034, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.955, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.688, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.754, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.628, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.114, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.498, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.868, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.679, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.217, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.716, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.259, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.479, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 24.254, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.792, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q1" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0029/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0029/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0029/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-t0029/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0041/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-t0041/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0041/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0041/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-t0041/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..49142df1b1048896707d25982f2da2ebd8bd0621 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0041/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R006,south,1,2,5,5,5,5,4 +R457,north,3,4,4,3,3,3,4 +R168,north,3,4,3,1,3,2,4 +R122,north,3,3,3,3,4,3,3 +R449,south,3,3,3,2,2,2,1 +R048,south,2,3,3,2,3,1,4 +R465,east,2,1,2,4,4,5,5 +R349,north,3,4,3,2,2,2,2 +R433,north,4,2,3,2,4,4,4 +R412,south,3,4,3,3,3,2,2 +R401,south,4,2,3,3,4,4,4 +R463,north,2,4,2,3,2,3,2 +R466,north,3,1,3,4,5,5,5 +R350,east,4,4,5,3,2,2,4 +R343,north,3,4,1,2,4,3,2 +R106,south,2,2,2,3,4,3,5 +R208,east,1,2,4,3,4,4,5 +R342,east,1,1,2,5,4,5,4 +R238,south,4,4,3,3,3,4,3 +R042,south,2,3,2,3,1,3,2 +R290,north,4,5,3,2,2,1,1 +R468,north,1,1,3,4,4,5,5 +R054,east,3,4,3,1,2,2,2 +R446,east,2,3,1,2,3,4,4 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0041/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-t0041/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..53a459d9d944755aa465f1b06cddcd4d2b4ed7a1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0041/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q1, q2. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0041/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-t0041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77ee978731cb0acb32127e2ea141307e54c85217 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0041/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Study Motivation Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0041/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-t0041/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0041/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0041/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0041/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0041/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0041/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-t0041/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..64c28f73d87721ae90fbc170bff3c0cff4e96e87 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0041/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-t0041/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-t0041/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..b71b9b2a7ed774dd94dd0d1c0f2eb5c3b707b0df --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0041/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.027, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.466, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.471, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.82, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.984, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.033, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.101, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.732, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.129, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.721, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.65, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.778, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.723, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.724, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 33.259, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.848, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q3" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0041/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0041/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0041/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-t0041/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0053/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-t0053/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0053/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0053/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-t0053/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..7bc2854048c70ba925fd862b116fd450718d8e3c --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0053/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R158,east,4,3,2,2,4,3,4 +R014,north,3,4,2,5,3,5,5 +R359,north,1,3,4,2,3,2,3 +R067,south,5,1,4,3,2,2,3 +R263,north,1,1,5,3,5,2,2 +R350,south,3,3,3,2,4,4,4 +R383,north,2,2,5,1,2,1,3 +R482,north,3,3,4,2,3,4,2 +R312,east,2,3,1,4,2,3,4 +R390,east,3,5,2,2,3,4,2 +R378,north,3,4,2,5,2,4,3 +R137,north,3,3,3,3,4,3,2 +R135,north,5,4,3,3,3,2,3 +R302,east,1,3,4,1,2,3,2 +R073,east,3,3,2,3,2,3,4 +R308,east,4,3,1,2,3,4,4 +R071,south,2,3,4,2,3,2,3 +R270,north,2,3,3,3,3,2,1 +R336,south,3,3,2,3,2,3,4 +R144,south,3,4,5,4,3,2,3 +R403,north,4,4,3,4,2,3,2 +R372,north,4,2,4,2,2,3,2 +R131,south,4,3,2,3,2,1,4 +R254,north,4,5,1,4,3,4,4 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0053/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-t0053/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..2360f78d5683c667a8bd977b5e3bc7f9abed66af --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0053/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q3, q5. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0053/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-t0053/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..936067e908d6c50de1e9261d1e84f306cca99001 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0053/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0053/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-t0053/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0053/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0053/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0053/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0053/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0053/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-t0053/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..77156991279bd58d37ccf9e1bc690cefa67c306d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0053/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-t0053/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-t0053/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..be101bcc0d9ddf556891bee1e63ab8a483b80f17 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0053/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.304, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.369, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.984, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.506, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.607, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.719, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.188, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.453, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 0.694, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.124, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.071, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.448, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 0.998, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.452, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 20.897, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.729, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q5" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0053/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0053/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0053/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-t0053/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0065/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-t0065/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0065/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0065/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-t0065/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..bb30bf76683faf7ebafb79fb0ab20947d85213c4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0065/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R058,east,2,2,4,3,5,2,3 +R049,north,4,2,1,3,3,2,4 +R487,north,3,3,1,3,3,4,2 +R037,east,4,2,2,3,3,3,3 +R265,east,2,4,5,3,1,5,2 +R356,east,1,3,3,2,4,1,2 +R415,east,4,4,5,4,2,4,2 +R275,east,3,3,5,4,1,4,2 +R002,east,2,4,3,5,3,2,3 +R217,north,3,3,4,4,2,4,2 +R157,east,3,3,2,3,5,3,4 +R432,north,3,2,1,2,4,1,3 +R386,south,2,4,3,4,2,3,4 +R467,east,4,2,3,3,3,2,2 +R296,south,4,3,3,3,2,4,2 +R246,east,3,3,3,4,4,3,2 +R366,south,3,5,4,5,3,5,2 +R381,east,3,2,1,2,4,1,5 +R206,east,3,5,2,4,3,3,2 +R499,east,4,3,5,4,1,3,4 +R298,east,3,4,5,5,1,4,1 +R403,north,4,3,4,3,4,3,3 +R072,east,2,3,4,3,3,5,4 +R044,south,3,5,3,4,3,5,2 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0065/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-t0065/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..2a0dd21ac3c321f02747f49004b142e69f069f40 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0065/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q5, q7. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0065/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-t0065/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..936067e908d6c50de1e9261d1e84f306cca99001 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0065/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0065/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-t0065/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0065/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0065/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0065/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0065/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0065/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-t0065/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a366b5020df0abd8eb17157765ee5655936bf4c5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0065/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-t0065/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-t0065/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4077f688b0610b11e65fb00b5182237ba643e176 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0065/tests/checks.json @@ -0,0 +1,123 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 0.696, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.01, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.955, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.566, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.884, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.594, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 0.781, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.678, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.418, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.636, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.623, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.694, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 0.998, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.48, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 25.993, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.792, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q1" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0065/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0065/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0065/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-t0065/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0077/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d2-t0077/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0077/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0077/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d2-t0077/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..0ee7c299163520aacf8e848310580b39d7fca80d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0077/environment/workdir/item_responses.csv @@ -0,0 +1,25 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7 +R138,north,2,3,3,4,4,3,3 +R032,south,2,3,2,3,3,3,3 +R078,east,4,3,2,2,3,3,4 +R041,south,1,3,2,5,4,3,3 +R441,east,2,5,1,4,4,2,1 +R426,east,5,2,3,3,3,2,2 +R165,north,5,2,3,3,2,2,3 +R137,north,1,3,3,2,4,3,3 +R001,south,1,3,1,2,5,3,3 +R313,north,3,5,3,2,4,3,4 +R135,north,2,5,1,4,4,1,2 +R286,east,3,3,3,4,3,3,4 +R121,east,4,1,5,4,1,3,4 +R143,south,3,3,4,2,3,5,5 +R466,north,2,4,2,3,4,3,1 +R019,east,3,2,3,3,3,4,5 +R176,south,4,1,3,2,2,4,3 +R491,north,3,2,2,4,2,1,4 +R432,east,1,4,2,2,5,1,2 +R404,north,3,4,3,3,3,4,1 +R492,south,3,4,5,2,3,3,3 +R202,north,2,3,2,2,2,2,3 +R127,south,2,3,3,3,4,3,2 +R010,east,2,4,2,2,4,3,1 diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0077/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d2-t0077/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..687f5dcb136f24ecfd4473f8b743b312dc1677c7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0077/environment/workdir/reliability_notes.md @@ -0,0 +1,15 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q2, q5. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0077/instruction.md b/tasks/psychometrics/psychometrics-reliability-d2-t0077/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..936067e908d6c50de1e9261d1e84f306cca99001 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0077/instruction.md @@ -0,0 +1,14 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 24 people to the 7 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q7`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 7-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0077/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d2-t0077/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0077/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0077/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0077/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0077/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0077/task.toml b/tasks/psychometrics/psychometrics-reliability-d2-t0077/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..135713a368673b181a022e705c49dc9c044527e8 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0077/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d2-t0077/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d2-t0077/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2e472024085395bca45690617e48d4845e18f448 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d2-t0077/tests/checks.json @@ -0,0 +1,124 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.375, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.56, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.245, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.651, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.114, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.593, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 0.862, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": -0.061, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 0.998, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.726, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 0.955, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.259, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.418, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.493, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 21.819, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.741, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q4", + "q6" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d2-t0077/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d2-t0077/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d2-t0077/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d2-t0077/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-e0009/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-e0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0009/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-e0009/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..ae17b9ad9a3c52970c6eedca23ae1910f77951be --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0009/environment/workdir/item_responses.csv @@ -0,0 +1,34 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R273,east,2,5,4,3,1,4,4,4 +R309,east,3,4,4,2,3,4,,3 +R092,south,2,4,2,2,5,1,1,1 +R114,south,3,4,1,3,4,2,2,1 +R037,east,3,3,4,3,1,2,3,3 +R061,east,1,4,3,1,5,2,2,1 +R222,east,2,3,1,2,5,2,1,1 +R315,south,2,4,3,2,2,4,3,3 +R011,east,3,4,3,5,4,3,4,4 +R339,east,4,2,3,1,4,2,2,5 +R190,south,3,3,2,3,3,4,2,4 +R482,north,1,3,3,3,4,3,3,3 +R474,south,3,4,3,1,3,,1,3 +R102,east,2,3,4,3,3,4,2,4 +R034,east,3,4,1,2,4,2,2,2 +R455,south,2,2,2,1,5,1,2,1 +R089,east,3,4,4,4,3,4,2,3 +R059,south,1,4,2,3,4,3,2,4 +R487,south,3,3,2,1,4,2,1,2 +R322,south,1,4,1,1,3,3,1,1 +R156,north,2,3,2,5,2,4,3,3 +R113,south,2,3,2,2,4,4,3,2 +R218,south,3,4,3,3,3,3,2,3 +R167,east,4,4,4,1,3,5,5,4 +R236,east,4,5,4,3,3,3,5,3 +R115,north,4,4,3,3,2,4,3,4 +R006,north,3,,4,,3,2,3,2 +R404,east,2,3,4,2,3,3,3,4 +R297,east,3,3,2,3,2,2,3,4 +R386,east,4,3,3,4,2,3,5,4 +R149,east,3,4,1,1,3,2,1,1 +R213,east,4,3,3,3,3,4,3,4 +R100,east,2,4,3,3,4,4,2,3 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0009/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-e0009/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..57e02f445edfee66b7eb9e1ca39033ebe5ed5653 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0009/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q2, q5. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0009/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-e0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5d83da3d812e89b124b16928a303f5c9ca35080b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0009/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 33 people to the 8 items of the Study Motivation Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0009/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-e0009/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0009/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0009/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-e0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0009/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0009/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-e0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ff5286b650692c17a7f8bc51c41505f7c970c70e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "eval"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-e0009/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-e0009/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4635c0b607964eb100fcff5e0b4f4413913608a6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0009/tests/checks.json @@ -0,0 +1,212 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 0.938, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.38, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.785, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.533, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": -0.151, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.836, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.068, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.607, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.751, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.292, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.445, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.777, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.237, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.588, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.752, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.068, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.546, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.76, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.357, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.684, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.734, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 1.568, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": 0.785, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.712, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 29.413, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.791, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q2" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q2", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.045, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0009/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-e0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-e0009/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-e0009/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-e0021/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-e0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0021/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-e0021/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..d2d2925d0195ef921ff8f091d9240e169644f4b5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0021/environment/workdir/item_responses.csv @@ -0,0 +1,35 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R053,north,2,3,4,3,2,5,3,2 +R331,north,4,4,3,3,4,3,1,5 +R432,south,3,3,2,3,2,2,2,4 +R239,east,4,4,3,2,4,3,1,4 +R202,east,2,5,3,4,3,2,4, +R276,north,2,2,2,3,3,5,4,1 +R313,north,1,3,3,3,2,3,3,2 +R476,east,1,1,1,2,3,4,5,1 +R351,south,4,3,2,3,3,3,1,5 +R429,east,3,2,4,4,3,1,2,4 +R112,east,1,1,3,1,1,5,5,2 +R418,east,3,4,4,2,,3,3, +R210,south,4,5,3,4,4,2,1,5 +R155,east,2,2,3,2,1,3,4,1 +R368,east,3,3,2,5,4,3,3,4 +R261,east,3,2,4,2,2,4,3,4 +R106,east,3,5,4,4,3,3,2,5 +R224,north,4,1,3,3,3,4,4,4 +R496,east,2,3,3,4,2,3,3,2 +R067,north,2,4,1,4,2,3,3,3 +R492,north,2,2,3,4,3,2,4,2 +R110,north,2,1,3,4,3,3,4,1 +R033,east,2,3,3,3,3,3,2,3 +R302,north,4,4,3,4,5,3,3,4 +R326,east,1,1,2,1,2,4,4,2 +R184,east,4,2,2,3,,2,3,3 +R084,south,4,5,2,5,2,2,1,5 +R377,south,5,4,4,3,5,1,1,4 +R173,south,3,2,3,2,3,3,1,3 +R199,east,4,5,3,5,4,3,3,4 +R249,north,3,3,4,,5,2,2,3 +R406,north,2,1,3,3,1,3,5,1 +R288,south,2,3,4,2,2,5,5,2 +R028,east,3,2,4,3,2,4,4,1 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0021/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-e0021/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..7f6bf4b80feb4eb6dcd8c62797afd9c08934bd77 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0021/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q6, q7. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0021/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-e0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7a6103cec33d81ca9ff065187df583fc0f2b8a9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0021/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 34 people to the 8 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0021/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-e0021/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0021/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0021/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-e0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0021/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0021/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-e0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e70bd063ff4e001267b1423207a60faf8ade8169 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "eval"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-e0021/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-e0021/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4b106c2399525465c3ac79b53876b3eb6d7195fb --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-e0021/tests/checks.json @@ -0,0 +1,212 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.237, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.812, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.828, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.752, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.727, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.835, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.714, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.081, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.892, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.154, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.492, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.861, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.151, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.615, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.849, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.109, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.588, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.852, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.886, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.773, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.829, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 2.069, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": 0.789, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.827, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 45.582, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.865, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q3" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q3", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.027, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-e0021/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-e0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-e0021/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-e0021/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0009/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-t0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0009/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-t0009/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..a17874939d42a5814999b0c98149858831bb3551 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0009/environment/workdir/item_responses.csv @@ -0,0 +1,34 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R175,north,3,3,3,2,3,3,3,3 +R463,south,4,4,5,,2,3,2,3 +R370,south,2,3,2,4,2,3,4,4 +R418,south,3,3,4,3,3,2,3,3 +R322,north,3,4,2,4,2,4,2,4 +R135,east,3,3,2,5,2,3,1,4 +R170,south,4,3,1,4,2,2,2,3 +R001,north,4,4,1,2,2,4,2,3 +R293,south,4,2,4,2,3,2,2,4 +R014,east,3,3,5,3,2,4,3,3 +R094,north,2,4,5,4,4,2,4,3 +R273,south,3,4,3,5,5,5,3,3 +R079,north,4,3,3,5,3,3,2,4 +R419,south,3,3,2,2,4,4,3,3 +R086,east,3,3,4,,3,3,3, +R491,south,5,4,3,5,4,5,2,3 +R364,east,3,2,4,2,4,3,3,4 +R078,south,4,3,2,4,3,4,2,2 +R004,south,2,5,4,3,4,3,2,3 +R074,north,4,5,4,4,2,4,2,2 +R053,north,4,2,3,2,3,3,4,4 +R113,south,2,2,4,3,3,3,3,2 +R142,north,3,3,1,3,2,2,3,2 +R231,south,4,4,3,4,3,3,3,3 +R260,south,3,4,3,5,4,3,3,5 +R188,south,3,2,4,2,3,1,5,4 +R341,north,3,2,3,2,3,3,3,3 +R289,east,3,3,3,3,4,2,3,3 +R471,south,4,3,3,3,2,4,2,3 +R049,south,2,3,3,4,3,3,4,2 +R062,north,4,5,2,4,2,5,2,4 +R216,north,3,2,3,2,2,2,3,3 +R213,north,4,,2,3,4,5,2,4 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0009/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-t0009/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..a404990bcb2375f9921041236f688fd71d809d96 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0009/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q3, q7. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0009/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-t0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..93a7a2814394ccfa29684749fb01d5167ebece57 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0009/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 33 people to the 8 items of the Everyday Coping Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0009/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-t0009/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0009/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0009/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0009/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0009/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-t0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1ea328cd9cb87ce1c27f66f166a419e9ac178b01 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-t0009/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-t0009/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..52f45bf7d8d3dd0077cabed112fce69e78844ea4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0009/tests/checks.json @@ -0,0 +1,214 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 0.599, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.355, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.553, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.855, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.511, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.499, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.137, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.175, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.609, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.195, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.485, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.497, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 0.754, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": -0.128, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.675, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.016, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.546, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.479, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 0.737, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.493, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.509, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 0.579, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": 0.017, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.633, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 14.424, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.598, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q3", + "q5", + "q8" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q5", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.077, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0009/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0009/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-t0009/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0021/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-t0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0021/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-t0021/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..640d191721ec6c9c44e07ecdaeab3d3bb697be3e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0021/environment/workdir/item_responses.csv @@ -0,0 +1,34 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R372,south,3,4,2,3,2,,2,1 +R364,east,3,2,2,3,2,4,2,1 +R081,south,5,2,2,2,2,3,2,3 +R043,south,2,3,4,3,3,4,2,5 +R029,south,4,1,4,3,3,2,4,3 +R079,north,1,2,5,5,5,1,5,5 +R184,north,2,4,2,3,4,3,2,2 +R232,east,4,3,2,2,2,5,3,1 +R283,north,4,3,2,3,3,4,2,2 +R370,south,3,3,3,3,2,3,2,4 +R312,east,2,3,2,4,5,2,5,4 +R485,north,3,5,2,2,3,3,2,2 +R182,south,2,3,3,3,4,1,4,3 +R082,north,4,3,3,4,3,3,1,3 +R224,south,4,2,1,4,3,4,3,2 +R175,north,1,3,4,5,5,1,3,5 +R073,north,4,2,3,2,4,4,3,3 +R477,east,3,4,3,2,3,2,4,3 +R004,south,3,5,4,2,4,2,4,4 +R070,east,3,2,2,3,2,3,3,3 +R385,east,4,,2,2,1,4,,1 +R297,east,4,2,2,3,3,4,3,2 +R471,south,3,4,5,3,3,2,3,4 +R138,north,3,2,4,3,5,,3,3 +R294,east,4,4,2,3,2,3,5,5 +R461,north,2,5,4,3,3,3,5,5 +R433,north,4,3,4,5,4,3,4,3 +R458,east,2,3,2,3,4,3,3,5 +R315,south,1,3,4,4,5,1,4,5 +R386,east,3,2,2,3,2,3,3,4 +R069,south,3,2,4,2,3,3,5,2 +R264,north,3,3,1,3,2,4,1,1 +R373,south,2,2,3,4,4,3,4,5 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0021/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-t0021/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..f6208dcc5fe13a50207820c5522eecf521c81c69 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0021/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q1, q6. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0021/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-t0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff8f91b288439760622b1c765751f7cf3681761c --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0021/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 33 people to the 8 items of the Work Engagement Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0021/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-t0021/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0021/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0021/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0021/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0021/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-t0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d9e35b40f57c24b6cb08366537e6e49ba22ff5c6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-t0021/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-t0021/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5d7d07e4934949ca6d21be7e066594f1a57663e1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0021/tests/checks.json @@ -0,0 +1,212 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.099, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.665, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.786, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.03, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.114, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.854, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.223, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.608, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.794, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 0.809, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.406, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.819, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.013, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.693, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.784, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.085, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.742, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.776, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.407, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.492, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.811, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 1.803, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": 0.682, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.782, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 33.844, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.823, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q2" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q2", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.031, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0021/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0021/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-t0021/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0033/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-t0033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0033/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0033/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-t0033/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..4a200f311a9a8a4e3a44813d6fb9edb359f130c2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0033/environment/workdir/item_responses.csv @@ -0,0 +1,36 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R157,south,4,4,2,,3,,3,4 +R315,south,2,1,4,4,3,1,3,1 +R301,north,2,3,2,2,1,4,3,3 +R412,east,4,3,4,4,5,1,3,3 +R245,north,3,3,3,2,3,4,3,2 +R478,south,4,3,3,4,4,3,4,3 +R259,east,2,2,4,3,3,3,4,3 +R055,south,3,4,3,4,4,3,3,1 +R115,south,2,2,4,3,4,3,2,3 +R159,south,4,4,4,4,4,1,5,2 +R461,north,4,4,4,2,5,2,4,1 +R230,south,3,3,4,4,3,2,3,3 +R105,south,2,3,3,4,3,3,3,2 +R074,south,5,5,2,4,3,3,3,4 +R411,north,3,4,3,3,2,4,1,4 +R099,south,2,2,3,3,3,5,3,3 +R111,north,2,3,3,1,3,4,2,4 +R364,east,4,3,4,4,4,2,4,3 +R437,north,2,3,2,5,4,3,2,3 +R453,east,2,3,2,3,2,,2,4 +R394,north,1,2,3,3,2,4,4,2 +R273,east,2,4,2,2,1,5,2,4 +R389,north,3,3,3,4,2,4,2,3 +R116,north,3,3,3,4,2,3,4,3 +R272,south,4,3,3,4,5,2,5,1 +R150,east,3,2,2,1,4,3,3,4 +R138,south,3,2,2,3,3,4,2, +R465,south,2,4,3,2,3,5,1,4 +R121,east,3,3,2,4,3,3,2,4 +R091,east,2,2,3,2,3,3,3,4 +R341,east,2,3,,4,3,4,,2 +R098,east,4,4,3,5,5,1,5,1 +R136,south,4,3,1,3,3,2,4,3 +R170,south,1,4,1,2,1,4,3,5 +R432,north,3,4,5,,4,1,4,2 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0033/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-t0033/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..4d93b4fb838c34f8918e8dd45717eeb13a937881 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0033/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q6, q8. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0033/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-t0033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..526c0f99ec5eaeab2d100f17b867c576f76d3611 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0033/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 35 people to the 8 items of the Study Motivation Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0033/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-t0033/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0033/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0033/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0033/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0033/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0033/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-t0033/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf8d618034760f6d828bfc1a3fe270c3896f31c0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0033/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-t0033/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-t0033/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..916ff3a351b35fc857379db746c9e0e5ccf0a0b5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0033/tests/checks.json @@ -0,0 +1,212 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.04, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.635, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.772, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.754, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.009, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.847, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.754, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.373, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.808, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.2, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.524, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.788, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.316, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.684, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.762, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.379, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.762, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.748, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.128, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.566, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.782, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 1.223, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": 0.609, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.775, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 30.185, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.81, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q2" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q2", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.037, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0033/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0033/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0033/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-t0033/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0045/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-t0045/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0045/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0045/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-t0045/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..1dc2fd1f7baaeed59f68a8dec7318a0e1dce53f6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0045/environment/workdir/item_responses.csv @@ -0,0 +1,34 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R009,south,3,5,3,3,3,4,3,3 +R437,east,3,2,5,3,4,1,4,2 +R027,north,2,3,3,4,2,3,4,2 +R355,south,3,3,3,3,3,3,3,2 +R264,south,1,2,3,3,2,3,2,4 +R308,south,3,3,4,5,5,3,2,2 +R451,east,3,4,5,4,3,4,4,3 +R165,east,3,4,3,4,3,3,3,2 +R147,north,2,5,4,2,2,2,3,4 +R060,north,4,,3,3,3,2,3,3 +R237,north,5,2,4,4,5,3,3,1 +R124,north,1,3,3,4,3,5,2,3 +R486,east,2,3,3,2,2,5,2,4 +R081,east,4,3,3,4,4,3,3,4 +R321,east,3,5,3,2,2,3,1,4 +R011,east,2,1,3,4,2,4,2,2 +R447,south,2,4,2,4,1,4,4,3 +R370,east,3,3,2,3,3,2,4, +R300,east,3,4,2,2,3,4,2,3 +R224,east,4,1,5,5,5,2,5,1 +R336,east,5,3,4,5,5,4,4,2 +R039,south,3,1,2,2,3,1,4,5 +R234,south,4,3,5,4,4,3,3,1 +R414,south,2,2,2,2,2,4,2,1 +R117,east,2,4,4,3,4,3,3,4 +R012,south,3,4,3,3,2,4,,5 +R155,east,4,2,4,3,4,3,4,2 +R296,north,3,3,1,1,1,2,2,5 +R449,east,3,3,4,3,5,2,3,3 +R221,east,4,3,3,4,4,3,5,3 +R479,south,3,3,3,3,4,4,3,2 +R439,north,5,3,4,4,4,2,1,3 +R050,north,2,5,2,2,2,3,3,3 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0045/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-t0045/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..35b180c01396a5360f20549fc19d283c3678af9a --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0045/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q2, q8. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0045/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-t0045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0c55e7a4bce09e0be521bf9392855c34a95f0b9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0045/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 33 people to the 8 items of the Social Confidence Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0045/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-t0045/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0045/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0045/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0045/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0045/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0045/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-t0045/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..11e8a725256da8d7d7d74d9f2b6a745be247b05c --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0045/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-t0045/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-t0045/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..802e16974e1421bbab1bc9600f6f44ecc219c10b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0045/tests/checks.json @@ -0,0 +1,213 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.137, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.47, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.699, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.306, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.263, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.74, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.045, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.582, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.678, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.099, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.718, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.648, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.476, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.698, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.644, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 0.99, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": -0.183, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.806, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 1.068, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.342, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.723, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 1.289, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": 0.613, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.667, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 26.309, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.734, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q2", + "q6" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q6", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.072, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0045/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0045/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0045/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-t0045/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0057/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-t0057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0057/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0057/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-t0057/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..2a171abc5f0ec6d10b9e772f3accd69757817389 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0057/environment/workdir/item_responses.csv @@ -0,0 +1,34 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R384,east,3,5,2,4,4,3,4,2 +R188,south,4,2,5,5,1,3,2,4 +R091,south,4,3,4,5,3,3,3,4 +R194,south,,4,4,4,,2,4,3 +R288,south,4,2,3,3,2,2,3,3 +R115,north,2,4,3,3,2,2,3,2 +R164,east,3,4,3,2,2,4,3,1 +R318,north,3,1,4,4,1,3,3,4 +R202,east,3,2,4,3,3,2,3,1 +R211,south,5,2,3,3,3,2,1,3 +R086,south,3,3,2,3,4,3,1,1 +R155,south,2,2,1,3,3,3,3,3 +R171,north,3,3,3,2,5,4,4,3 +R019,east,2,4,2,2,4,2,3,2 +R257,east,4,1,5,4,2,3,3,4 +R045,south,2,4,4,1,3,3,3,3 +R005,north,2,2,5,3,2,4,3,3 +R494,south,3,4,2,3,3,2,3,2 +R336,east,1,3,3,2,2,3,3,2 +R492,east,2,4,1,3,3,2,3,3 +R434,east,1,,3,2,3,4,2,3 +R476,east,3,5,2,2,5,4,2,2 +R410,north,3,3,2,4,4,4,5,4 +R366,south,3,1,3,3,3,3,3,3 +R263,east,4,3,5,1,3,3,3,3 +R082,south,4,2,4,5,1,4,3,4 +R200,east,1,4,3,4,3,3,3,3 +R008,south,3,4,3,4,3,3,3,3 +R268,east,3,,3,3,3,4,4,5 +R416,north,4,2,4,5,2,4,5,5 +R493,north,3,3,3,3,4,3,2,2 +R121,east,3,3,4,2,3,4,2,4 +R009,north,1,4,2,2,3,3,3,1 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0057/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-t0057/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..57e02f445edfee66b7eb9e1ca39033ebe5ed5653 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0057/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q2, q5. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0057/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-t0057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff8f91b288439760622b1c765751f7cf3681761c --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0057/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 33 people to the 8 items of the Work Engagement Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0057/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-t0057/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0057/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0057/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0057/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0057/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0057/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-t0057/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..26e42bec1328f273d2925f7e08bc50888634e7c4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0057/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-t0057/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-t0057/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5234f410a6832036a540d5a980b56e76f7a0de3e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0057/tests/checks.json @@ -0,0 +1,213 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 0.99, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.429, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.741, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 1.275, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.582, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.712, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.292, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.557, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.717, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.266, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.512, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.726, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.085, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.492, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.73, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 0.516, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.21, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.77, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 0.754, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.126, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.785, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 1.131, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": 0.72, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.685, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 24.892, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.761, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q6", + "q7" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q7", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.023, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0057/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0057/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0057/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-t0057/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0069/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-t0069/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0069/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0069/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-t0069/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..6c30720f9854bea2fd84b07393af262bb04c3745 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0069/environment/workdir/item_responses.csv @@ -0,0 +1,34 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R285,north,3,3,4,3,3,4,2,3 +R078,north,3,3,2,2,3,2,3,3 +R026,north,3,3,2,3,2,2,3,2 +R383,south,4,2,3,2,4,3,2,4 +R280,south,3,5,3,4,3,2,2,4 +R424,south,2,3,4,2,3,3,4,3 +R204,east,1,5,1,1,5,2,1,3 +R434,south,3,2,3,2,2,4,3,2 +R263,north,5,2,4,3,1,5,5,2 +R186,east,4,1,5,5,3,3,5,3 +R076,south,5,2,5,5,1,4,3,2 +R075,north,5,3,4,4,2,5,4,3 +R409,north,4,3,3,4,1,3,3,4 +R068,north,2,3,1,3,4,4,3,3 +R009,north,4,3,5,5,1,4,4,2 +R049,north,1,3,2,2,4,4,3, +R378,south,1,2,4,2,3,3,4,4 +R140,east,4,1,3,4,1,3,4,3 +R034,south,4,1,4,4,4,4,4,2 +R208,north,2,3,2,4,4,3,3,3 +R376,east,3,,3,2,3,2,2,4 +R304,north,3,3,3,4,4,4,2,4 +R319,east,3,4,2,2,3,2,2,4 +R127,east,3,3,2,3,3,4,2,4 +R273,south,2,3,4,3,5,2,3,1 +R433,east,2,2,3,4,4,3,3,2 +R041,south,2,,,4,2,4,2,3 +R189,north,5,2,3,2,3,1,3,3 +R196,south,2,3,5,4,3,2,2,2 +R318,south,2,3,3,3,4,3,3,5 +R253,south,5,2,5,5,1,5,5,3 +R337,east,3,3,1,2,3,4,3,3 +R330,south,4,3,3,2,4,2,3,1 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0069/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-t0069/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..57e02f445edfee66b7eb9e1ca39033ebe5ed5653 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0069/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q2, q5. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0069/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-t0069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0c55e7a4bce09e0be521bf9392855c34a95f0b9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0069/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 33 people to the 8 items of the Social Confidence Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0069/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-t0069/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0069/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0069/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0069/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0069/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0069/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-t0069/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5156c491c0a01f1456e5003872f79f12f973d2c5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0069/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-t0069/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-t0069/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d3c4674ea7927ca7f948c0a543b68790ceec1bcb --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0069/tests/checks.json @@ -0,0 +1,212 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.407, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.6, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.73, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.907, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.526, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.746, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 1.476, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.558, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.738, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.269, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.592, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.732, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 1.472, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.634, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.723, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.109, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.514, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.747, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 0.99, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.655, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.725, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 0.921, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": -0.208, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.843, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 29.799, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.777, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q8" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q8", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.066, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0069/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0069/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0069/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-t0069/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0081/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliability-d3-t0081/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0081/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0081/environment/workdir/item_responses.csv b/tasks/psychometrics/psychometrics-reliability-d3-t0081/environment/workdir/item_responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..82824085c231d876202bd7d1ebdfe8db955a7150 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0081/environment/workdir/item_responses.csv @@ -0,0 +1,36 @@ +respondent_id,site,q1,q2,q3,q4,q5,q6,q7,q8 +R158,south,2,3,2,2,2,4,4,4 +R084,east,1,2,3,2,2,5,3,4 +R182,east,2,4,2,3,3,5,3,4 +R156,east,4,5,5,5,4,3,1,4 +R351,south,3,3,4,5,3,2,2,3 +R443,east,3,4,,4,2,3,2,3 +R341,east,4,4,4,4,5,2,2,2 +R420,north,1,3,2,4,2,,5,3 +R048,north,,,4,3,4,3,2,4 +R414,north,3,2,4,3,4,2,2,3 +R454,north,3,4,3,3,3,3,4,3 +R150,north,2,3,3,5,4,4,3,3 +R467,south,2,2,3,3,3,4,3,2 +R089,south,3,4,2,1,3,3,4,3 +R456,north,1,2,,3,3,3,3,2 +R227,east,1,2,2,2,3,5,4,2 +R112,south,2,4,2,2,3,5,3,3 +R421,north,2,3,2,4,2,3,3,3 +R065,east,2,2,2,3,2,4,4,5 +R001,north,5,3,4,4,4,2,2,3 +R487,north,4,3,3,2,2,4,3,3 +R006,east,4,3,2,,3,2,3,4 +R022,east,3,4,2,4,2,4,3,3 +R094,south,4,3,5,3,3,3,2,4 +R162,south,4,4,4,5,4,2,2,3 +R283,south,4,4,4,4,4,3,2,4 +R379,east,3,2,3,2,3,4,4,3 +R265,east,2,3,3,3,4,2,2,3 +R447,east,4,4,4,4,5,2,2,2 +R203,east,3,4,2,3,2,4,3,3 +R229,east,2,2,3,3,2,4,3,3 +R101,east,4,4,3,2,2,1,4,3 +R352,south,2,2,2,1,2,4,4,5 +R362,east,4,5,5,4,3,3,1,3 +R193,north,3,3,3,3,3,3,3,3 diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0081/environment/workdir/reliability_notes.md b/tasks/psychometrics/psychometrics-reliability-d3-t0081/environment/workdir/reliability_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..7f6bf4b80feb4eb6dcd8c62797afd9c08934bd77 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0081/environment/workdir/reliability_notes.md @@ -0,0 +1,18 @@ +# Reliability analysis: definitions + +The scale is invented for practice. Every item is answered from 1 to 5. + +Reverse-keyed items: q6, q7. For these the item score is 6 minus the response. Reverse them first; every figure below is computed from item scores. + +A respondent with one or more empty cells is left out of the whole analysis (listwise deletion). + +With `k` items and `n` respondents: + +- The variance of a set of `n` values is the sample variance: the sum of squared deviations from the mean, divided by `n - 1`. +- A respondent's total is the sum of the `k` item scores. +- Cronbach's alpha: + + alpha = k / (k - 1) * (1 - (sum of the k item variances) / (variance of the totals)) +- The corrected item-total correlation of an item is the Pearson correlation, across respondents, between that item's score and the sum of the other `k - 1` item scores (the total without that item). +- An item is weak if its corrected item-total correlation is below 0.30. +- Alpha if item deleted is Cronbach's alpha computed on the other `k - 1` items only (so with `k - 1` in place of `k` everywhere). diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0081/instruction.md b/tasks/psychometrics/psychometrics-reliability-d3-t0081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..efbe490e08ea3c2ff5d98322348f7eba91329331 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0081/instruction.md @@ -0,0 +1,18 @@ +# Reliability of a scale + +`item_responses.csv` holds the responses of 35 people to the 8 items of the Work Engagement Scale, one row per respondent. `reliability_notes.md` gives the definitions to use, including which items are reverse-keyed and what to do with incomplete rows. + +Write `answer.json` in this folder, a JSON object with: + +- `items`: an object keyed by item name (`q1` to `q8`). Each value has + - `variance`: the variance of the item scores, 3 decimals. + - `item_rest_r`: the corrected item-total correlation, 3 decimals. + - `alpha_if_deleted`: Cronbach's alpha of the scale without this item, 3 decimals. +- `total_variance`: the variance of the respondents' totals, 3 decimals. +- `alpha`: Cronbach's alpha of the 8-item scale, 3 decimals. +- `weak_items`: list of the items whose corrected item-total correlation is below 0.30 (any order; an empty list if none). +- `n_used`: the number of respondents kept in the analysis, an integer. +- `best_item_to_drop`: the item with the highest alpha if item deleted. +- `alpha_gain`: that item's alpha if item deleted minus `alpha`, 3 decimals (negative if dropping it would lower alpha). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0081/solution/oracle.py b/tasks/psychometrics/psychometrics-reliability-d3-t0081/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0081/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0081/solution/solve.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0081/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0081/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0081/task.toml b/tasks/psychometrics/psychometrics-reliability-d3-t0081/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7afbeba5b93c17d3175ec6a9397a0accf9b7cd7a --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0081/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliability", "isced-0313", "train"] +isced_f = "0313" +family = "reliability" +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/psychometrics/psychometrics-reliability-d3-t0081/tests/checks.json b/tasks/psychometrics/psychometrics-reliability-d3-t0081/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4a56eeabd58c500bed0caef511cbf918a262eb92 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-d3-t0081/tests/checks.json @@ -0,0 +1,212 @@ +[ + { + "path": "items.q1.variance", + "type": "number", + "value": 1.059, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.item_rest_r", + "type": "number", + "value": 0.718, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q1.alpha_if_deleted", + "type": "number", + "value": 0.772, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.variance", + "type": "number", + "value": 0.875, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.item_rest_r", + "type": "number", + "value": 0.482, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q2.alpha_if_deleted", + "type": "number", + "value": 0.807, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.variance", + "type": "number", + "value": 0.99, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.item_rest_r", + "type": "number", + "value": 0.789, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q3.alpha_if_deleted", + "type": "number", + "value": 0.762, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.variance", + "type": "number", + "value": 1.292, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.item_rest_r", + "type": "number", + "value": 0.621, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q4.alpha_if_deleted", + "type": "number", + "value": 0.787, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.variance", + "type": "number", + "value": 0.861, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.item_rest_r", + "type": "number", + "value": 0.585, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q5.alpha_if_deleted", + "type": "number", + "value": 0.793, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.variance", + "type": "number", + "value": 1.183, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.item_rest_r", + "type": "number", + "value": 0.592, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q6.alpha_if_deleted", + "type": "number", + "value": 0.792, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.variance", + "type": "number", + "value": 0.833, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.item_rest_r", + "type": "number", + "value": 0.782, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q7.alpha_if_deleted", + "type": "number", + "value": 0.767, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.variance", + "type": "number", + "value": 0.579, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.item_rest_r", + "type": "number", + "value": -0.259, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "items.q8.alpha_if_deleted", + "type": "number", + "value": 0.878, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "total_variance", + "type": "number", + "value": 27.154, + "abs_tol": 0.001, + "weight": 1.0 + }, + { + "path": "alpha", + "type": "number", + "value": 0.82, + "abs_tol": 0.001, + "weight": 2 + }, + { + "path": "weak_items", + "type": "set", + "value": [ + "q8" + ], + "item": "str", + "weight": 2 + }, + { + "path": "n_used", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "best_item_to_drop", + "type": "str", + "value": "q8", + "weight": 2 + }, + { + "path": "alpha_gain", + "type": "number", + "value": 0.058, + "abs_tol": 0.001, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliability-d3-t0081/tests/test.sh b/tasks/psychometrics/psychometrics-reliability-d3-t0081/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliability-d3-t0081/tests/verify.py b/tasks/psychometrics/psychometrics-reliability-d3-t0081/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliability-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/psychometrics/psychometrics-reliable-change-d1-e0002/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..b9b89ea2f51da9b93f82728a62ad48116402988c --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,7,0-30,6.2,0.75,12 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..3903d77a015ab6917ebddf43acd96da9d92028b2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C132,SLQ,19,8,12,T2 +C271,SLQ,20,15,15,T3 +C326,SLQ,14,13,19,T3 +C364,SLQ,26,12,17,T2 +C325,SLQ,25,9,15,T3 +C161,SLQ,23,8,12,T1 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d1436eb19320cd1b0d46c8266fe4b04f1c47a59 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "eval"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-e0002/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..9501ec2eea76ab241a2bff8907612500fc2dc7a7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/tests/checks.json @@ -0,0 +1,105 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 4.38, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C132.SLQ.rci", + "type": "number", + "value": -2.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C132.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C161.SLQ.rci", + "type": "number", + "value": -3.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C161.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C271.SLQ.rci", + "type": "number", + "value": -1.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C271.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C325.SLQ.rci", + "type": "number", + "value": -3.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C325.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C326.SLQ.rci", + "type": "number", + "value": -0.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C326.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C364.SLQ.rci", + "type": "number", + "value": -3.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C364.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C132:SLQ", + "C161:SLQ", + "C325:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-e0002/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-e0002/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-e0014/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..de9af029b02678eb7cd671699f35a75a8fb0371d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SC,Stress Checklist,13,0-40,7.3,0.81,20 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..62c09204bb4f8bc90ea9498e50e66f40a0daad43 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C130,SC,20,1,20,T3 +C228,SC,28,17,14,T1 +C213,SC,4,4,9,T1 +C184,SC,22,34,10,T3 +C372,SC,27,10,8,T1 +C208,SC,18,6,12,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c2cdf89898011acd96f6cb52cbdebe5571429dbe --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "eval"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-e0014/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..eb28b78366ce9feb2b33fb536f4e6d18c1e71804 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/tests/checks.json @@ -0,0 +1,107 @@ +[ + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 4.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C130.SC.rci", + "type": "number", + "value": -4.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C130.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C184.SC.rci", + "type": "number", + "value": 2.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C184.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C208.SC.rci", + "type": "number", + "value": -2.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C208.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C213.SC.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C213.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C228.SC.rci", + "type": "number", + "value": -2.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C228.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C372.SC.rci", + "type": "number", + "value": -3.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C372.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C130:SC", + "C228:SC", + "C372:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C184:SC" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-e0014/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-e0014/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0002/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..6f524a21532664f22b261acded13b71ff25fd45b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,7,0-30,6.8,0.82,12 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f1ca2e782e9be048c34c556435f6a06fc74cb6d8 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C326,SLQ,17,4,18,T2 +C331,SLQ,24,14,19,T3 +C143,SLQ,19,4,15,T1 +C232,SLQ,25,15,15,T3 +C163,SLQ,22,21,17,T2 +C204,SLQ,28,23,15,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3c77a44d3afb5052bfdca3ab9c5ef8d7d36ede7b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-t0002/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c2d22a10e79f846f640be324b81e8f7f3d4cd14d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/tests/checks.json @@ -0,0 +1,104 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 4.08, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C143.SLQ.rci", + "type": "number", + "value": -3.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C143.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C163.SLQ.rci", + "type": "number", + "value": -0.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C163.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C204.SLQ.rci", + "type": "number", + "value": -1.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C204.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C232.SLQ.rci", + "type": "number", + "value": -2.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C232.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C326.SLQ.rci", + "type": "number", + "value": -3.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C326.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C331.SLQ.rci", + "type": "number", + "value": -2.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C331.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C143:SLQ", + "C326:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0002/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0002/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0014/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..e3c59c649228045158ba7ead81a2fb93ddaa3f76 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +MI,Mood Inventory,12,0-36,7.2,0.82,14 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..52859897483953d0a15f0259f097bb6fb89dc620 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C391,MI,25,35,7,T2 +C318,MI,5,7,14,T1 +C202,MI,22,3,13,T3 +C239,MI,31,20,12,T2 +C227,MI,19,25,16,T3 +C364,MI,31,26,8,T2 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7cef6494ee89ff1d82af02a3287e7bb75603e0a3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-t0014/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..966190953515827b40074f095e65cc430bda028b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/tests/checks.json @@ -0,0 +1,105 @@ +[ + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 4.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C202.MI.rci", + "type": "number", + "value": -4.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C202.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C227.MI.rci", + "type": "number", + "value": 1.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C227.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C239.MI.rci", + "type": "number", + "value": -2.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C239.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C318.MI.rci", + "type": "number", + "value": 0.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C318.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C364.MI.rci", + "type": "number", + "value": -1.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C364.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C391.MI.rci", + "type": "number", + "value": 2.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C391.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C202:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C391:MI" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0014/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0014/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0026/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..a71264adbff6920af97804b3ce10d7c7fba5e691 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SC,Stress Checklist,13,0-40,8.8,0.84,18 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..3f225543042ec660beb0f283b846db681e4daf1f --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C194,SC,31,34,17,T1 +C253,SC,14,26,13,T2 +C339,SC,26,4,18,T2 +C114,SC,13,0,9,T2 +C171,SC,24,12,13,T3 +C349,SC,18,11,11,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..05cec39186296ebacc4df1578ba6e6819f5ba23a --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-t0026/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c41efd0ad28a2635174d7265062c0578ea306eea --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/tests/checks.json @@ -0,0 +1,106 @@ +[ + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 4.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C114.SC.rci", + "type": "number", + "value": -2.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C114.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C171.SC.rci", + "type": "number", + "value": -2.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C171.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C194.SC.rci", + "type": "number", + "value": 0.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C194.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C253.SC.rci", + "type": "number", + "value": 2.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C253.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C339.SC.rci", + "type": "number", + "value": -4.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C339.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C349.SC.rci", + "type": "number", + "value": -1.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C349.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C171:SC", + "C339:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C253:SC" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0026/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0026/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0038/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..7ab7ae8b09177d30623f9ee4eb5cbd07e168d639 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,7,0-30,5.7,0.76,13 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..ae970e1e770c1906986b98060485c8d419723c23 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C245,SLQ,18,23,17,T1 +C151,SLQ,26,16,12,T2 +C104,SLQ,14,26,12,T2 +C277,SLQ,4,19,18,T3 +C352,SLQ,18,7,19,T2 +C225,SLQ,18,1,20,T1 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d8b9ef60b4370cccb8944f59a67a256b49902fb3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-t0038/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a56062b9a9645f4dfb4555ebe1913fe9da7c2e5d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/tests/checks.json @@ -0,0 +1,107 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 3.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C104.SLQ.rci", + "type": "number", + "value": 3.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C104.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C151.SLQ.rci", + "type": "number", + "value": -2.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C151.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C225.SLQ.rci", + "type": "number", + "value": -4.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C225.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C245.SLQ.rci", + "type": "number", + "value": 1.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C245.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C277.SLQ.rci", + "type": "number", + "value": 3.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C277.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C352.SLQ.rci", + "type": "number", + "value": -2.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C352.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C225:SLQ", + "C352:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C104:SLQ", + "C277:SLQ" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0038/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0038/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0050/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..49ff3d11a0eb4c06d45c843a2638d420a85ae9a9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +WQ,Worry Questionnaire,16,0-48,5.7,0.85,19 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..60a1e9dbd55b495823c3deb72099fc4b40886a29 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C397,WQ,29,15,16,T3 +C157,WQ,13,13,12,T2 +C178,WQ,37,25,13,T2 +C219,WQ,16,5,17,T3 +C366,WQ,36,35,8,T1 +C398,WQ,13,9,16,T1 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..18b7e059b9a223ce6216f14cb72e31b9c70c5805 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-t0050/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..275cd631fd0b1733c15c031cdecdc5526665d619 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/tests/checks.json @@ -0,0 +1,103 @@ +[ + { + "path": "instruments.WQ.s_diff", + "type": "number", + "value": 3.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C157.WQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C157.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C178.WQ.rci", + "type": "number", + "value": -3.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C178.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C219.WQ.rci", + "type": "number", + "value": -3.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C219.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C366.WQ.rci", + "type": "number", + "value": -0.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C366.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C397.WQ.rci", + "type": "number", + "value": -4.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C397.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C398.WQ.rci", + "type": "number", + "value": -1.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C398.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C397:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0050/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0050/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0062/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..c82b3ff7d1c96f62c87926d5994638e24880326d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SC,Stress Checklist,10,0-40,5.2,0.89,20 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..522565d38976c125ef8fb6656f8d1ac4ab93446a --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C212,SC,34,25,8,T1 +C124,SC,10,2,9,T2 +C104,SC,30,32,16,T1 +C289,SC,35,26,11,T3 +C106,SC,28,34,9,T2 +C192,SC,25,16,15,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7dcff62a8929e27eb7e9920de40900a88a58e54b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-t0062/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..a1523f70d2e5f00dc21c00d078bcee431a3bd997 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/tests/checks.json @@ -0,0 +1,105 @@ +[ + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 2.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C104.SC.rci", + "type": "number", + "value": 0.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C104.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C106.SC.rci", + "type": "number", + "value": 2.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C106.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C124.SC.rci", + "type": "number", + "value": -3.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C124.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C192.SC.rci", + "type": "number", + "value": -3.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C192.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C212.SC.rci", + "type": "number", + "value": -3.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C212.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C289.SC.rci", + "type": "number", + "value": -3.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C289.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C192:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C106:SC" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0062/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0062/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0074/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..93cf00540dd79e9c9b3be954bd55c2003ab4b03a --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/instruments.csv @@ -0,0 +1,2 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,10,0-30,6.1,0.77,13 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..e19d19342ea96f94b0f4eade808c200309f1c7bc --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/outcomes.csv @@ -0,0 +1,7 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C164,SLQ,19,2,15,T1 +C206,SLQ,19,18,11,T3 +C293,SLQ,6,6,17,T1 +C260,SLQ,2,15,11,T1 +C112,SLQ,19,4,16,T3 +C366,SLQ,26,16,19,T1 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eadd31751bcca364ad259a4eeaff710f407d172e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/instruction.md @@ -0,0 +1,15 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on one instrument, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea237a1a45d47a91a3ba8cda6956496ac3b08d23 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d1-t0074/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..4897ec9b455928445e3ebe38f7f7c01bebee4e2e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/tests/checks.json @@ -0,0 +1,106 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 4.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C112.SLQ.rci", + "type": "number", + "value": -3.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C112.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C164.SLQ.rci", + "type": "number", + "value": -4.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C164.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C206.SLQ.rci", + "type": "number", + "value": -0.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C206.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C260.SLQ.rci", + "type": "number", + "value": 3.14, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C260.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C293.SLQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C293.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C366.SLQ.rci", + "type": "number", + "value": -2.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C366.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C112:SLQ", + "C164:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C260:SLQ" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d1-t0074/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d1-t0074/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-e0006/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..63d2756db27784ae8149f0a1271570ef2dc3f61b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,10,0-30,6.7,0.86,12 +MI,Mood Inventory,9,0-36,5.0,0.75,18 +SC,Stress Checklist,10,0-40,6.7,0.78,20 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..ab19cf659fb3a80ed8db566f5fc0f37cc8c62cf5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C123,SC,33,21,12,T1 +C254,SC,33,,1,T1 +C211,MI,32,19,7,T3 +C284,SC,24,30,17,T1 +C110,MI,18,30,9,T1 +C110,SC,36,31,18,T2 +C354,SC,22,24,6,T1 +C284,MI,19,10,15,T3 +C234,MI,16,1,13,T1 +C254,MI,33,31,6,T3 +C211,SC,31,18,10,T3 +C354,MI,13,4,19,T3 +C234,SC,29,,2,T3 +C123,MI,22,8,11,T3 +C217,MI,12,17,10,T2 +C217,SC,23,17,14,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e8d5299f56a186c887c0b09a72acb73e69aa147c --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "eval"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-e0006/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..83beb738b432fb4cab9c367df7f3b58a75cd0034 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/tests/checks.json @@ -0,0 +1,228 @@ +[ + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 3.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 4.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C110.MI.rci", + "type": "number", + "value": 3.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C110.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C110.SC.rci", + "type": "number", + "value": -1.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C110.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C123.MI.rci", + "type": "number", + "value": -3.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C123.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C123.SC.rci", + "type": "number", + "value": -2.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C123.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C211.MI.rci", + "type": "number", + "value": -3.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C211.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C211.SC.rci", + "type": "number", + "value": -2.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C211.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C217.MI.rci", + "type": "number", + "value": 1.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C217.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C217.SC.rci", + "type": "number", + "value": -1.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C217.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C234.MI.rci", + "type": "number", + "value": -4.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C234.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C254.MI.rci", + "type": "number", + "value": -0.57, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C254.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C284.MI.rci", + "type": "number", + "value": -2.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C284.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C284.SC.rci", + "type": "number", + "value": 1.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C284.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C354.MI.rci", + "type": "number", + "value": -2.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C354.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C354.SC.rci", + "type": "number", + "value": 0.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C354.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C123:MI", + "C211:SC", + "C284:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C110:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C234:SC", + "C254:SC" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-e0006/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-e0006/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-e0018/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..41c2086bfac3fc1b4e042a510f3a77ebb1d44edf --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SC,Stress Checklist,13,0-40,7.3,0.79,18 +SLQ,Sleep Problems Questionnaire,7,0-30,8.0,0.89,12 +WQ,Worry Questionnaire,16,0-48,8.8,0.77,24 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..150230dc31aa7e73fde329b3d2a21d36401c7117 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C276,WQ,36,15,9,T2 +C239,WQ,28,13,15,T1 +C302,SC,33,36,9,T3 +C192,SC,33,31,12,T2 +C133,SC,8,10,9,T3 +C155,WQ,45,26,19,T3 +C239,SC,21,28,20,T2 +C116,SC,25,,4,T2 +C133,WQ,33,34,14,T1 +C175,WQ,40,25,7,T3 +C175,SC,29,34,7,T1 +C302,WQ,30,47,16,T2 +C192,WQ,18,0,14,T1 +C116,WQ,2,0,16,T1 +C276,SC,6,22,9,T2 +C155,SC,38,26,7,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..90eaa8daafd99320b115da309ba8f66e8955febb --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "eval"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-e0018/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..73f7b5da3d5873e735d9360871e531b87fc36613 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/tests/checks.json @@ -0,0 +1,240 @@ +[ + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 4.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.WQ.s_diff", + "type": "number", + "value": 5.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C116.WQ.rci", + "type": "number", + "value": -0.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C116.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C133.SC.rci", + "type": "number", + "value": 0.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C133.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C133.WQ.rci", + "type": "number", + "value": 0.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C133.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C155.SC.rci", + "type": "number", + "value": -2.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C155.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C155.WQ.rci", + "type": "number", + "value": -3.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C155.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C175.SC.rci", + "type": "number", + "value": 1.06, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C175.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C175.WQ.rci", + "type": "number", + "value": -2.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C175.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C192.SC.rci", + "type": "number", + "value": -0.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C192.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C192.WQ.rci", + "type": "number", + "value": -3.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C192.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C239.SC.rci", + "type": "number", + "value": 1.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C239.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C239.WQ.rci", + "type": "number", + "value": -2.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C239.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C276.SC.rci", + "type": "number", + "value": 3.38, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C276.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C276.WQ.rci", + "type": "number", + "value": -3.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C276.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C302.SC.rci", + "type": "number", + "value": 0.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C302.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C302.WQ.rci", + "type": "number", + "value": 2.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C302.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C239:WQ", + "C276:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C276:SC", + "C302:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C116:SC" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-e0018/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-e0018/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0006/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..2fe64cd8a7d51a812fa2fdcd2a152f7e257061f5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,10,0-30,5.9,0.84,13 +MI,Mood Inventory,12,0-36,5.1,0.87,18 +SC,Stress Checklist,13,0-40,7.1,0.87,16 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..5d247b8a139b4e9b71027bc3302b2d070fd969e0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C190,MI,23,17,13,T3 +C132,MI,31,28,18,T3 +C293,MI,30,20,7,T2 +C293,SLQ,26,,2,T2 +C151,MI,19,12,6,T3 +C171,MI,18,12,17,T2 +C190,SLQ,21,12,8,T3 +C132,SLQ,17,26,10,T1 +C240,MI,30,33,6,T2 +C379,MI,11,14,12,T3 +C379,SLQ,17,4,13,T2 +C306,MI,29,35,12,T1 +C240,SLQ,14,0,13,T3 +C151,SLQ,25,,2,T3 +C171,SLQ,28,30,9,T1 +C306,SLQ,25,13,13,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9840953ac2fdb2a35c6115f29d9aca61b64a72af --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-t0006/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2a799b4fa6585c3e76bf5106b9bcee8133d06128 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/tests/checks.json @@ -0,0 +1,232 @@ +[ + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 2.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 3.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C132.MI.rci", + "type": "number", + "value": -1.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C132.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C132.SLQ.rci", + "type": "number", + "value": 2.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C132.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C151.MI.rci", + "type": "number", + "value": -2.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C151.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C171.MI.rci", + "type": "number", + "value": -2.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C171.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C171.SLQ.rci", + "type": "number", + "value": 0.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C171.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C190.MI.rci", + "type": "number", + "value": -2.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C190.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C190.SLQ.rci", + "type": "number", + "value": -2.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C190.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C240.MI.rci", + "type": "number", + "value": 1.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C240.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C240.SLQ.rci", + "type": "number", + "value": -4.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C240.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C293.MI.rci", + "type": "number", + "value": -3.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C293.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C306.MI.rci", + "type": "number", + "value": 2.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C306.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C306.SLQ.rci", + "type": "number", + "value": -3.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C306.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C379.MI.rci", + "type": "number", + "value": 1.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C379.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C379.SLQ.rci", + "type": "number", + "value": -3.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C379.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C151:MI", + "C171:MI", + "C190:MI", + "C190:SLQ", + "C240:SLQ", + "C379:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C132:SLQ", + "C306:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C151:SLQ", + "C293:SLQ" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0006/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0006/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0018/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..f13c42dde6f897ab95587f47c2ea49dd318a5d63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +MI,Mood Inventory,12,0-36,8.4,0.89,14 +SLQ,Sleep Problems Questionnaire,10,0-30,7.1,0.77,15 +SC,Stress Checklist,10,0-40,5.0,0.85,18 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..50748a7f9c18f23890e1886c72fdb41bf6fcf0f6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C134,MI,30,13,17,T3 +C257,SLQ,21,22,18,T3 +C234,SLQ,17,2,9,T2 +C111,MI,2,14,14,T3 +C111,SLQ,19,19,16,T2 +C177,SLQ,10,,4,T3 +C154,MI,27,14,8,T2 +C154,SLQ,9,25,13,T3 +C396,MI,5,10,18,T1 +C112,SLQ,26,22,10,T1 +C396,SLQ,27,23,14,T1 +C177,MI,26,9,19,T1 +C134,SLQ,16,,3,T2 +C234,MI,14,4,8,T2 +C112,MI,24,8,20,T2 +C257,MI,22,5,11,T2 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c639a46331d3878de90182fd3bc9fad333e2d526 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-t0018/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..0f638ade02f3ecfd5b7bbedaf3a843d677880b74 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/tests/checks.json @@ -0,0 +1,232 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 4.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 3.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C111.SLQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C111.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C111.MI.rci", + "type": "number", + "value": 3.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C111.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C112.SLQ.rci", + "type": "number", + "value": -0.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C112.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C112.MI.rci", + "type": "number", + "value": -4.06, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C112.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C134.MI.rci", + "type": "number", + "value": -4.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C134.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C154.SLQ.rci", + "type": "number", + "value": 3.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C154.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C154.MI.rci", + "type": "number", + "value": -3.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C154.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C177.MI.rci", + "type": "number", + "value": -4.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C177.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C234.SLQ.rci", + "type": "number", + "value": -3.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C234.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C234.MI.rci", + "type": "number", + "value": -2.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C234.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C257.SLQ.rci", + "type": "number", + "value": 0.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C257.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C257.MI.rci", + "type": "number", + "value": -4.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C257.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C396.SLQ.rci", + "type": "number", + "value": -0.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C396.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C396.MI.rci", + "type": "number", + "value": 1.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C396.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C112:MI", + "C134:MI", + "C177:MI", + "C234:MI", + "C234:SLQ", + "C257:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C111:MI", + "C154:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C134:SLQ", + "C177:SLQ" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0018/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0018/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0030/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..7962258f9a10f93808e17730ffe6cbba0ccd49ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,7,0-30,8.1,0.87,12 +WQ,Worry Questionnaire,16,0-48,5.0,0.88,24 +SC,Stress Checklist,10,0-40,7.9,0.82,18 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2367b42b8f1cc14641b7db82381b9cff8979d6c2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C187,SC,26,14,15,T3 +C243,SC,21,36,20,T3 +C369,SC,19,22,15,T2 +C265,SC,26,37,10,T3 +C369,SLQ,8,9,20,T2 +C268,SLQ,21,9,20,T2 +C330,SC,17,16,7,T2 +C187,SLQ,14,,3,T1 +C396,SLQ,10,14,7,T2 +C396,SC,24,12,16,T3 +C268,SC,20,16,9,T2 +C265,SLQ,13,16,11,T3 +C243,SLQ,28,17,20,T1 +C194,SC,9,28,18,T3 +C194,SLQ,21,8,17,T1 +C330,SLQ,24,9,9,T2 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f6e3444cac11a70d30d07d66ec5b7fd30650b381 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-t0030/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..60899b4c97508eef52172352d0e95f3dbf18703d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/tests/checks.json @@ -0,0 +1,244 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 4.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 4.74, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C187.SC.rci", + "type": "number", + "value": -2.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C187.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C194.SLQ.rci", + "type": "number", + "value": -3.15, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C194.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C194.SC.rci", + "type": "number", + "value": 4.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C194.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C243.SLQ.rci", + "type": "number", + "value": -2.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C243.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C243.SC.rci", + "type": "number", + "value": 3.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C243.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C265.SLQ.rci", + "type": "number", + "value": 0.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C265.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C265.SC.rci", + "type": "number", + "value": 2.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C265.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C268.SLQ.rci", + "type": "number", + "value": -2.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C268.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C268.SC.rci", + "type": "number", + "value": -0.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C268.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C330.SLQ.rci", + "type": "number", + "value": -3.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C330.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C330.SC.rci", + "type": "number", + "value": -0.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C330.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C369.SLQ.rci", + "type": "number", + "value": 0.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C369.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C369.SC.rci", + "type": "number", + "value": 0.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C369.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C396.SLQ.rci", + "type": "number", + "value": 0.97, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C396.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C396.SC.rci", + "type": "number", + "value": -2.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C396.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C187:SC", + "C194:SLQ", + "C268:SLQ", + "C330:SLQ", + "C396:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C194:SC", + "C243:SC", + "C265:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C187:SLQ" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0030/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0030/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0042/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..887542cfae912c714e81447c61aad2223ad6d6df --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,10,0-30,7.9,0.79,15 +WQ,Worry Questionnaire,16,0-48,8.3,0.86,21 +MI,Mood Inventory,12,0-36,7.4,0.89,16 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..88d1f08cad792d8a3abbeb9a599df1532c1973f2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C246,MI,2,15,17,T1 +C391,MI,18,9,17,T3 +C224,MI,6,18,11,T1 +C312,MI,29,20,19,T2 +C292,SLQ,7,5,19,T3 +C229,MI,26,29,6,T2 +C316,SLQ,23,1,17,T1 +C316,MI,32,,3,T2 +C224,SLQ,22,16,7,T1 +C239,SLQ,20,0,10,T3 +C391,SLQ,27,6,16,T2 +C292,MI,34,35,18,T1 +C312,SLQ,22,5,20,T2 +C246,SLQ,23,11,13,T2 +C239,MI,24,11,16,T1 +C229,SLQ,14,16,17,T1 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3ddc2a7c32777aa6ba89facb04801eb637bab2d7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-t0042/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6a82115b91382c193b797a216d3389f73994d834 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/tests/checks.json @@ -0,0 +1,245 @@ +[ + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 3.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 5.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C224.MI.rci", + "type": "number", + "value": 3.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C224.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C224.SLQ.rci", + "type": "number", + "value": -1.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C224.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C229.MI.rci", + "type": "number", + "value": 0.86, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C229.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C229.SLQ.rci", + "type": "number", + "value": 0.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C229.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C239.MI.rci", + "type": "number", + "value": -3.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C239.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C239.SLQ.rci", + "type": "number", + "value": -3.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C239.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C246.MI.rci", + "type": "number", + "value": 3.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C246.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C246.SLQ.rci", + "type": "number", + "value": -2.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C246.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C292.MI.rci", + "type": "number", + "value": 0.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C292.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C292.SLQ.rci", + "type": "number", + "value": -0.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C292.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C312.MI.rci", + "type": "number", + "value": -2.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C312.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C312.SLQ.rci", + "type": "number", + "value": -3.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C312.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C316.SLQ.rci", + "type": "number", + "value": -4.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C316.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C391.MI.rci", + "type": "number", + "value": -2.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C391.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C391.SLQ.rci", + "type": "number", + "value": -4.1, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C391.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C239:MI", + "C239:SLQ", + "C246:SLQ", + "C312:SLQ", + "C316:SLQ", + "C391:MI", + "C391:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C224:MI", + "C246:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C316:MI" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0042/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0042/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0054/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..c8b4b420ea5451c02d9fd9fda22ebea97e777ea8 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +MI,Mood Inventory,12,0-36,8.7,0.79,16 +SC,Stress Checklist,10,0-40,9.0,0.85,20 +SLQ,Sleep Problems Questionnaire,7,0-30,6.6,0.81,15 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..cf0804c4ec571d9974e85624666623e8d5922961 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C250,MI,8,24,7,T1 +C268,SLQ,26,14,18,T2 +C227,MI,34,18,10,T3 +C120,MI,27,23,6,T2 +C356,SLQ,28,28,6,T3 +C367,SLQ,24,23,18,T2 +C179,MI,33,33,19,T3 +C227,SLQ,20,,4,T1 +C268,MI,13,14,16,T1 +C179,SLQ,16,2,14,T1 +C267,SLQ,18,0,12,T1 +C120,SLQ,24,13,12,T2 +C356,MI,27,27,6,T1 +C267,MI,32,,2,T1 +C367,MI,32,18,16,T3 +C250,SLQ,2,14,18,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ffcb2dbd59cec6a0da4dab4578d94d38c137a7b6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-t0054/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e9f4ca50585d19eb8e7e98e6dca68078dcb47cfd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/tests/checks.json @@ -0,0 +1,230 @@ +[ + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 5.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 4.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C120.MI.rci", + "type": "number", + "value": -0.71, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C120.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C120.SLQ.rci", + "type": "number", + "value": -2.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C120.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C179.MI.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C179.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C179.SLQ.rci", + "type": "number", + "value": -3.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C179.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C227.MI.rci", + "type": "number", + "value": -2.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C227.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C250.MI.rci", + "type": "number", + "value": 2.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C250.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C250.SLQ.rci", + "type": "number", + "value": 2.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C250.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C267.SLQ.rci", + "type": "number", + "value": -4.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C267.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C268.MI.rci", + "type": "number", + "value": 0.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C268.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C268.SLQ.rci", + "type": "number", + "value": -2.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C268.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C356.MI.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C356.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C356.SLQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C356.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C367.MI.rci", + "type": "number", + "value": -2.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C367.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C367.SLQ.rci", + "type": "number", + "value": -0.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C367.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C120:SLQ", + "C179:SLQ", + "C267:SLQ", + "C268:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C250:MI", + "C250:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C227:SLQ", + "C267:MI" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0054/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0054/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0066/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..efdb3129ea4aad853653c82113c022c723e6cc3f --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SC,Stress Checklist,13,0-40,6.6,0.75,16 +MI,Mood Inventory,9,0-36,5.9,0.90,14 +WQ,Worry Questionnaire,12,0-48,5.3,0.75,21 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..663bf8db394a30cf36be699ab36a1aa82f98b1a0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C141,WQ,27,11,12,T2 +C382,SC,9,26,17,T1 +C348,SC,33,19,12,T1 +C187,WQ,33,18,8,T3 +C221,WQ,45,28,18,T1 +C114,WQ,18,5,16,T1 +C281,WQ,40,45,8,T3 +C382,WQ,2,,3,T3 +C348,WQ,37,40,17,T1 +C187,SC,27,10,10,T2 +C281,SC,16,1,9,T2 +C221,SC,36,37,9,T1 +C141,SC,33,,3,T2 +C356,WQ,32,30,14,T2 +C114,SC,35,19,7,T3 +C356,SC,21,8,7,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..20475ecdfcd8c7304cce247d1ac8a914f2f08ca5 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-t0066/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d50483a52c109a224017b0b5dd972889c9eb5682 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/tests/checks.json @@ -0,0 +1,230 @@ +[ + { + "path": "instruments.WQ.s_diff", + "type": "number", + "value": 3.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 4.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C114.WQ.rci", + "type": "number", + "value": -3.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C114.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C114.SC.rci", + "type": "number", + "value": -3.43, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C114.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C141.WQ.rci", + "type": "number", + "value": -4.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C141.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C187.WQ.rci", + "type": "number", + "value": -4.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C187.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C187.SC.rci", + "type": "number", + "value": -3.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C187.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C221.WQ.rci", + "type": "number", + "value": -4.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C221.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C221.SC.rci", + "type": "number", + "value": 0.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C221.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C281.WQ.rci", + "type": "number", + "value": 1.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C281.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C281.SC.rci", + "type": "number", + "value": -3.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C281.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C348.WQ.rci", + "type": "number", + "value": 0.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C348.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C348.SC.rci", + "type": "number", + "value": -3.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C348.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C356.WQ.rci", + "type": "number", + "value": -0.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C356.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C356.SC.rci", + "type": "number", + "value": -2.79, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C356.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C382.SC.rci", + "type": "number", + "value": 3.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C382.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C141:WQ", + "C187:SC", + "C187:WQ", + "C281:SC", + "C356:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C382:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C141:SC", + "C382:WQ" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0066/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0066/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0078/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..57aeaeae3269dbad16fca587dac45df726d8e64e --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/instruments.csv @@ -0,0 +1,4 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff +SLQ,Sleep Problems Questionnaire,7,0-30,7.5,0.85,15 +MI,Mood Inventory,12,0-36,8.6,0.92,16 +SC,Stress Checklist,13,0-40,8.0,0.89,18 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..6dac8701635f6574c2c4f99af05ecab073f885c9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/outcomes.csv @@ -0,0 +1,17 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C360,SLQ,27,14,13,T2 +C183,MI,17,16,15,T3 +C183,SLQ,12,1,20,T1 +C360,MI,6,2,6,T3 +C332,SLQ,18,7,17,T2 +C332,MI,30,25,19,T3 +C343,MI,9,,3,T1 +C160,SLQ,9,6,10,T1 +C254,MI,10,14,6,T2 +C254,SLQ,12,,1,T3 +C333,SLQ,20,20,11,T1 +C160,MI,18,31,20,T3 +C144,SLQ,28,13,10,T1 +C343,SLQ,20,7,18,T2 +C333,MI,30,32,6,T2 +C144,MI,18,20,17,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1f7e73bde04c8c9f79291dbb6556b3cde0c218 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/environment/workdir/rci_rules.md @@ -0,0 +1,25 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +On every instrument here a higher score means more difficulties. A score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17604d288b5e7570f908f358211dc79b145d2d83 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/instruction.md @@ -0,0 +1,16 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 8 clients on 2 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..361ce5b5bb3df7dee598e9125667249084d30a89 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d2-t0078/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ceca215d82a0efdfe355a7e1d7229e0e02f0d705 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/tests/checks.json @@ -0,0 +1,229 @@ +[ + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 3.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 4.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C144.MI.rci", + "type": "number", + "value": 0.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C144.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C144.SLQ.rci", + "type": "number", + "value": -3.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C144.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C160.MI.rci", + "type": "number", + "value": 3.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C160.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C160.SLQ.rci", + "type": "number", + "value": -0.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C160.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C183.MI.rci", + "type": "number", + "value": -0.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C183.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C183.SLQ.rci", + "type": "number", + "value": -2.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C183.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C254.MI.rci", + "type": "number", + "value": 1.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C254.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C332.MI.rci", + "type": "number", + "value": -1.45, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C332.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C332.SLQ.rci", + "type": "number", + "value": -2.68, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C332.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C333.MI.rci", + "type": "number", + "value": 0.58, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C333.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C333.SLQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C333.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C343.SLQ.rci", + "type": "number", + "value": -3.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C343.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C360.MI.rci", + "type": "number", + "value": -1.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C360.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C360.SLQ.rci", + "type": "number", + "value": -3.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C360.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C144:SLQ", + "C332:SLQ", + "C343:SLQ", + "C360:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C160:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C254:SLQ", + "C343:MI" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d2-t0078/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d2-t0078/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-e0010/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..5d24678a614f4bf23ed41b58fcbcca9ab3ea9d41 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +MI,Mood Inventory,12,0-36,5.1,0.86,18,higher_is_worse +SC,Stress Checklist,10,0-40,6.3,0.88,20,higher_is_worse +WQ,Worry Questionnaire,16,0-48,8.5,0.85,24,higher_is_worse +DFS,Daily Functioning Scale,15,0-60,6.4,0.86,24,higher_is_better diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..ce6820e8660782525fe852f8dddec306fd760416 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C346,SC,14,1,10,T1 +C373,SC,23,31,20,T2 +C146,MI,16,13,11,T1 +C396,SC,32,18,7,T1 +C146,DFS,15,28,14,T1 +C346,DFS,48,56,6,T2 +C175,DFS,42,46,13,T2 +C396,MI,11,12,18,T3 +C175,SC,34,30,9,T3 +C113,DFS,35,46,14,T2 +C175,MI,19,10,14,T1 +C373,MI,30,,3,T1 +C113,MI,27,20,17,T2 +C346,MI,21,24,6,T2 +C373,DFS,19,21,18,T3 +C396,DFS,16,13,11,T1 +C146,SC,20,7,17,T1 +C113,SC,27,29,18,T1 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7ddfe528dcdb398a85216c113c34e9c91a85ac37 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "eval"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-e0010/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..25e6c9558323f07193e4b25dac61a1dbbd2fe327 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/tests/checks.json @@ -0,0 +1,295 @@ +[ + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 3.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 2.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.DFS.s_diff", + "type": "number", + "value": 3.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C113.SC.rci", + "type": "number", + "value": 0.65, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C113.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C113.MI.rci", + "type": "number", + "value": -2.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C113.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C113.DFS.rci", + "type": "number", + "value": 3.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C113.DFS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C146.SC.rci", + "type": "number", + "value": -4.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C146.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C146.MI.rci", + "type": "number", + "value": -1.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C146.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C146.DFS.rci", + "type": "number", + "value": 3.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C146.DFS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C175.SC.rci", + "type": "number", + "value": -1.3, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C175.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C175.MI.rci", + "type": "number", + "value": -3.33, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C175.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C175.DFS.rci", + "type": "number", + "value": 1.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C175.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C346.SC.rci", + "type": "number", + "value": -4.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C346.MI.rci", + "type": "number", + "value": 1.11, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C346.DFS.rci", + "type": "number", + "value": 2.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.DFS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C373.SC.rci", + "type": "number", + "value": 2.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C373.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C373.DFS.rci", + "type": "number", + "value": 0.59, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C373.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C396.SC.rci", + "type": "number", + "value": -4.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C396.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C396.MI.rci", + "type": "number", + "value": 0.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C396.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C396.DFS.rci", + "type": "number", + "value": -0.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C396.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C146:DFS", + "C146:SC", + "C175:MI", + "C396:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C373:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C373:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.SC.recovered_pct", + "type": "number", + "value": 33.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.MI.recovered_pct", + "type": "number", + "value": 20.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.DFS.recovered_pct", + "type": "number", + "value": 16.7, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-e0010/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-e0010/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-e0022/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..76cedd90d391f9cc9ba580fba85989254b88ac46 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +DFS,Daily Functioning Scale,15,0-60,8.7,0.90,27,higher_is_better +MI,Mood Inventory,9,0-36,8.1,0.83,18,higher_is_worse +WQ,Worry Questionnaire,12,0-48,8.9,0.90,19,higher_is_worse +SLQ,Sleep Problems Questionnaire,10,0-30,8.3,0.78,15,higher_is_worse diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..d775d2daf98110dccefd2e87fc41d1a99dbe79bc --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C257,DFS,55,46,10,T1 +C253,DFS,15,12,18,T1 +C121,SLQ,24,10,20,T2 +C310,SLQ,28,26,11,T1 +C310,DFS,5,7,11,T2 +C257,SLQ,19,,4,T1 +C200,SLQ,16,,3,T2 +C147,SLQ,7,21,9,T1 +C253,SLQ,23,9,10,T3 +C257,WQ,6,20,14,T2 +C200,DFS,9,12,12,T2 +C253,WQ,35,33,11,T1 +C200,WQ,31,15,19,T3 +C310,WQ,34,24,14,T2 +C147,DFS,17,17,17,T2 +C121,WQ,45,31,7,T1 +C121,DFS,14,1,10,T2 +C147,WQ,8,9,11,T1 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3ad045abedbfabea5992ede5d7d3584cccb2c36d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "eval"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-e0022/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f775c6a1d776f301baa10eaab92572c0e80cf388 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/tests/checks.json @@ -0,0 +1,285 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 5.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.WQ.s_diff", + "type": "number", + "value": 3.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.DFS.s_diff", + "type": "number", + "value": 3.89, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C121.SLQ.rci", + "type": "number", + "value": -2.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C121.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C121.WQ.rci", + "type": "number", + "value": -3.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C121.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C121.DFS.rci", + "type": "number", + "value": -3.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C121.DFS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C147.SLQ.rci", + "type": "number", + "value": 2.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C147.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C147.WQ.rci", + "type": "number", + "value": 0.25, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C147.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C147.DFS.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C147.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C200.WQ.rci", + "type": "number", + "value": -4.02, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C200.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C200.DFS.rci", + "type": "number", + "value": 0.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C200.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C253.SLQ.rci", + "type": "number", + "value": -2.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C253.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C253.WQ.rci", + "type": "number", + "value": -0.5, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C253.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C253.DFS.rci", + "type": "number", + "value": -0.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C253.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C257.WQ.rci", + "type": "number", + "value": 3.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C257.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C257.DFS.rci", + "type": "number", + "value": -2.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C257.DFS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C310.SLQ.rci", + "type": "number", + "value": -0.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C310.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C310.WQ.rci", + "type": "number", + "value": -2.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C310.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C310.DFS.rci", + "type": "number", + "value": 0.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C310.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C121:SLQ", + "C200:WQ", + "C253:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C121:DFS", + "C147:SLQ", + "C257:DFS", + "C257:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C200:SLQ", + "C257:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.SLQ.recovered_pct", + "type": "number", + "value": 50.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.WQ.recovered_pct", + "type": "number", + "value": 16.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.DFS.recovered_pct", + "type": "number", + "value": 0.0, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-e0022/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-e0022/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0010/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..0172cf2fb002acc01a894355f6251fb9f07433c6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +DFS,Daily Functioning Scale,20,0-60,7.6,0.88,30,higher_is_better +WBS,Wellbeing Scale,12,0-50,7.6,0.80,20,higher_is_better +MI,Mood Inventory,9,0-36,8.7,0.86,18,higher_is_worse +WQ,Worry Questionnaire,12,0-48,8.1,0.92,19,higher_is_worse diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..7c27671499926ae8ab32a3acd9795e29126da367 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C193,MI,19,31,15,T2 +C174,DFS,10,19,9,T1 +C228,MI,33,26,6,T2 +C193,DFS,25,40,18,T1 +C313,WQ,30,18,18,T3 +C313,MI,31,32,6,T1 +C193,WQ,21,30,18,T2 +C253,DFS,31,,1,T2 +C174,WQ,17,25,10,T3 +C248,DFS,7,24,19,T1 +C228,WQ,19,29,13,T1 +C253,WQ,19,6,16,T2 +C228,DFS,28,24,9,T2 +C253,MI,33,16,11,T3 +C174,MI,29,18,15,T3 +C248,WQ,10,20,20,T1 +C313,DFS,22,33,13,T1 +C248,MI,33,22,18,T2 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..600bdbec02f67c6dec5c01506c46a03a80e129f6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-t0010/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2639271ecbb2deaa5ff5270d69593175f12d701d --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/tests/checks.json @@ -0,0 +1,300 @@ +[ + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 4.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.WQ.s_diff", + "type": "number", + "value": 3.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.DFS.s_diff", + "type": "number", + "value": 3.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.MI.rci", + "type": "number", + "value": -2.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C174.WQ.rci", + "type": "number", + "value": 2.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C174.DFS.rci", + "type": "number", + "value": 2.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.DFS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C193.MI.rci", + "type": "number", + "value": 2.61, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C193.MI.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C193.WQ.rci", + "type": "number", + "value": 2.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C193.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C193.DFS.rci", + "type": "number", + "value": 4.03, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C193.DFS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C228.MI.rci", + "type": "number", + "value": -1.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C228.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C228.WQ.rci", + "type": "number", + "value": 3.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C228.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C228.DFS.rci", + "type": "number", + "value": -1.07, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C228.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C248.MI.rci", + "type": "number", + "value": -2.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C248.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C248.WQ.rci", + "type": "number", + "value": 3.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C248.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C248.DFS.rci", + "type": "number", + "value": 4.57, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C248.DFS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C253.MI.rci", + "type": "number", + "value": -3.69, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C253.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C253.WQ.rci", + "type": "number", + "value": -4.01, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C253.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C313.MI.rci", + "type": "number", + "value": 0.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C313.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C313.WQ.rci", + "type": "number", + "value": -3.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C313.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C313.DFS.rci", + "type": "number", + "value": 2.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C313.DFS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C193:DFS", + "C253:MI", + "C253:WQ", + "C313:DFS", + "C313:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C174:WQ", + "C193:MI", + "C193:WQ", + "C228:WQ", + "C248:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C253:DFS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.MI.recovered_pct", + "type": "number", + "value": 16.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.WQ.recovered_pct", + "type": "number", + "value": 33.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.DFS.recovered_pct", + "type": "number", + "value": 40.0, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0010/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0010/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0022/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..f49202f2a8bf45cb3aa5dd2e9e6b97627c7db309 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +WQ,Worry Questionnaire,12,0-48,8.8,0.92,19,higher_is_worse +DFS,Daily Functioning Scale,15,0-60,7.1,0.82,24,higher_is_better +WBS,Wellbeing Scale,12,0-50,7.2,0.78,20,higher_is_better +SC,Stress Checklist,13,0-40,6.3,0.80,20,higher_is_worse diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..6413418ce89b40199383d1f5b69feaeeeee03087 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C182,SC,20,26,13,T1 +C182,DFS,16,,2,T1 +C108,WQ,41,26,11,T3 +C175,DFS,17,29,9,T1 +C214,DFS,18,37,9,T3 +C175,SC,36,22,7,T2 +C346,WQ,42,39,12,T2 +C214,SC,34,20,7,T3 +C108,SC,34,,4,T3 +C346,DFS,10,15,9,T1 +C214,WQ,30,19,6,T2 +C108,DFS,6,10,6,T1 +C182,WQ,38,26,17,T3 +C328,DFS,15,18,11,T2 +C346,SC,21,8,20,T3 +C175,WQ,38,46,6,T3 +C328,SC,37,23,8,T3 +C328,WQ,43,31,8,T1 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bc1ab0ce447b12e413ffa9695ab18ea3baca5fbd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-t0022/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..943747735bcd129aa16998b53a30f9fbc2093a31 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/tests/checks.json @@ -0,0 +1,282 @@ +[ + { + "path": "instruments.WQ.s_diff", + "type": "number", + "value": 3.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 3.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.DFS.s_diff", + "type": "number", + "value": 4.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C108.WQ.rci", + "type": "number", + "value": -4.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C108.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C108.DFS.rci", + "type": "number", + "value": 0.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C108.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C175.WQ.rci", + "type": "number", + "value": 2.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C175.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C175.SC.rci", + "type": "number", + "value": -3.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C175.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C175.DFS.rci", + "type": "number", + "value": 2.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C175.DFS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C182.WQ.rci", + "type": "number", + "value": -3.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C182.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C182.SC.rci", + "type": "number", + "value": 1.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C182.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C214.WQ.rci", + "type": "number", + "value": -3.12, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C214.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C214.SC.rci", + "type": "number", + "value": -3.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C214.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C214.DFS.rci", + "type": "number", + "value": 4.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C214.DFS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C328.WQ.rci", + "type": "number", + "value": -3.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C328.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C328.SC.rci", + "type": "number", + "value": -3.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C328.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C328.DFS.rci", + "type": "number", + "value": 0.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C328.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C346.WQ.rci", + "type": "number", + "value": -0.85, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C346.SC.rci", + "type": "number", + "value": -3.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C346.DFS.rci", + "type": "number", + "value": 1.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C175:DFS", + "C214:DFS", + "C346:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C175:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C108:SC", + "C182:DFS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.WQ.recovered_pct", + "type": "number", + "value": 0.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.SC.recovered_pct", + "type": "number", + "value": 20.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.DFS.recovered_pct", + "type": "number", + "value": 40.0, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0022/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0022/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0034/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..55175ee1605c15f92dbe6f02004b2b324d538efc --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +SLQ,Sleep Problems Questionnaire,7,0-30,7.9,0.92,13,higher_is_worse +WBS,Wellbeing Scale,16,0-50,8.4,0.82,22,higher_is_better +MI,Mood Inventory,9,0-36,6.6,0.82,14,higher_is_worse +SC,Stress Checklist,13,0-40,8.4,0.87,20,higher_is_worse diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..63e796589ae194fba82eb40685690d704a7bfc79 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C357,SLQ,4,1,10,T1 +C174,SLQ,19,15,20,T2 +C237,SLQ,7,9,15,T1 +C307,WBS,4,25,12,T3 +C137,SLQ,15,5,8,T3 +C174,WBS,26,7,15,T1 +C237,WBS,21,15,13,T3 +C134,SLQ,17,29,9,T1 +C357,WBS,21,36,10,T1 +C137,SC,19,19,10,T1 +C307,SC,18,16,12,T3 +C137,WBS,4,18,18,T3 +C357,SC,7,7,8,T3 +C134,SC,8,,4,T2 +C237,SC,34,35,7,T3 +C174,SC,16,2,15,T2 +C307,SLQ,6,14,7,T3 +C134,WBS,24,7,8,T2 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..989ddf915fa195344de87951735328b71ccd2757 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-t0034/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..7ab9d41eb0188dff68c2ac31e828cb3b86d26135 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/tests/checks.json @@ -0,0 +1,297 @@ +[ + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 4.28, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 3.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.WBS.s_diff", + "type": "number", + "value": 5.04, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C134.SLQ.rci", + "type": "number", + "value": 3.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C134.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C134.WBS.rci", + "type": "number", + "value": -3.37, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C134.WBS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C137.SC.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C137.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C137.SLQ.rci", + "type": "number", + "value": -3.16, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C137.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C137.WBS.rci", + "type": "number", + "value": 2.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C137.WBS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C174.SC.rci", + "type": "number", + "value": -3.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.SC.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C174.SLQ.rci", + "type": "number", + "value": -1.27, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C174.WBS.rci", + "type": "number", + "value": -3.77, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.WBS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C237.SC.rci", + "type": "number", + "value": 0.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C237.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C237.SLQ.rci", + "type": "number", + "value": 0.63, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C237.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C237.WBS.rci", + "type": "number", + "value": -1.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C237.WBS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C307.SC.rci", + "type": "number", + "value": -0.47, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C307.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C307.SLQ.rci", + "type": "number", + "value": 2.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C307.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C307.WBS.rci", + "type": "number", + "value": 4.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C307.WBS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C357.SC.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C357.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C357.SLQ.rci", + "type": "number", + "value": -0.95, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C357.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C357.WBS.rci", + "type": "number", + "value": 2.98, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C357.WBS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C137:SLQ", + "C307:WBS", + "C357:WBS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C134:SLQ", + "C134:WBS", + "C174:WBS", + "C307:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C134:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.SC.recovered_pct", + "type": "number", + "value": 0.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.SLQ.recovered_pct", + "type": "number", + "value": 16.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.WBS.recovered_pct", + "type": "number", + "value": 33.3, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0034/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0034/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0046/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bed8eb13e4bb1011578130a8fa615090db78c85 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +SLQ,Sleep Problems Questionnaire,10,0-30,6.3,0.90,12,higher_is_worse +WQ,Worry Questionnaire,12,0-48,6.0,0.89,21,higher_is_worse +WBS,Wellbeing Scale,16,0-50,7.2,0.81,22,higher_is_better +SC,Stress Checklist,13,0-40,5.9,0.83,16,higher_is_worse diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..1aac66b9474d99cf373c350d00fc53c35dcc11d7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C129,SLQ,18,27,12,T3 +C246,WQ,44,48,17,T3 +C214,WQ,29,39,13,T1 +C225,WBS,14,20,14,T1 +C225,SLQ,12,12,18,T3 +C129,WBS,5,10,17,T2 +C140,WQ,12,16,11,T3 +C225,WQ,4,4,18,T2 +C335,WBS,18,30,20,T3 +C140,WBS,6,7,12,T2 +C246,WBS,6,,4,T1 +C214,WBS,34,50,11,T3 +C214,SLQ,13,2,20,T3 +C129,WQ,23,13,15,T2 +C335,SLQ,26,22,10,T3 +C335,WQ,41,30,6,T3 +C246,SLQ,12,6,16,T1 +C140,SLQ,19,19,15,T2 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2eadbcbdf96220fa35ab0c03d9b62b39c0b9f4c3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-t0046/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..f888f1bd4ce7b0171f1e90601b4ae001453050f8 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/tests/checks.json @@ -0,0 +1,296 @@ +[ + { + "path": "instruments.WQ.s_diff", + "type": "number", + "value": 2.81, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 2.82, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.WBS.s_diff", + "type": "number", + "value": 4.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C129.WQ.rci", + "type": "number", + "value": -3.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C129.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C129.SLQ.rci", + "type": "number", + "value": 3.19, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C129.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C129.WBS.rci", + "type": "number", + "value": 1.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C129.WBS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C140.WQ.rci", + "type": "number", + "value": 1.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C140.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C140.SLQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C140.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C140.WBS.rci", + "type": "number", + "value": 0.23, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C140.WBS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C214.WQ.rci", + "type": "number", + "value": 3.55, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C214.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C214.SLQ.rci", + "type": "number", + "value": -3.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C214.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C214.WBS.rci", + "type": "number", + "value": 3.6, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C214.WBS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C225.WQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C225.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C225.SLQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C225.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C225.WBS.rci", + "type": "number", + "value": 1.35, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C225.WBS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C246.WQ.rci", + "type": "number", + "value": 1.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C246.WQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C246.SLQ.rci", + "type": "number", + "value": -2.13, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C246.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C335.WQ.rci", + "type": "number", + "value": -3.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C335.WQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C335.SLQ.rci", + "type": "number", + "value": -1.42, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C335.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C335.WBS.rci", + "type": "number", + "value": 2.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C335.WBS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C129:WQ", + "C214:SLQ", + "C246:SLQ", + "C335:WBS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C129:SLQ", + "C214:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C246:WBS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.WQ.recovered_pct", + "type": "number", + "value": 16.7, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.SLQ.recovered_pct", + "type": "number", + "value": 33.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.WBS.recovered_pct", + "type": "number", + "value": 20.0, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0046/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0046/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0058/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..4ce78fac51ba45885dc0dc7da4b942397217477b --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +WQ,Worry Questionnaire,16,0-48,8.4,0.79,19,higher_is_worse +SLQ,Sleep Problems Questionnaire,7,0-30,6.4,0.80,12,higher_is_worse +DFS,Daily Functioning Scale,15,0-60,6.5,0.80,30,higher_is_better +WBS,Wellbeing Scale,16,0-50,8.7,0.79,22,higher_is_better diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..7be908a6106a4e2637e275730df3b56ed975d576 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C381,WQ,31,15,19,T1 +C267,SLQ,23,28,7,T3 +C267,WBS,22,29,16,T3 +C293,SLQ,25,13,15,T2 +C195,WBS,15,1,10,T3 +C381,SLQ,13,1,13,T3 +C267,WQ,10,24,14,T2 +C277,SLQ,22,,4,T3 +C382,SLQ,25,20,12,T1 +C277,WBS,21,5,12,T3 +C382,WQ,32,12,15,T2 +C195,WQ,28,9,16,T2 +C293,WQ,34,10,11,T2 +C195,SLQ,10,23,9,T2 +C277,WQ,31,15,13,T3 +C293,WBS,8,32,19,T3 +C381,WBS,11,,1,T3 +C382,WBS,7,29,10,T2 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f28fc5c38f60bd80a388e3c274c786e4d62e5354 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-t0058/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..e6ad5d8fd32d59adde0148e0930e4f66e0f0f477 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/tests/checks.json @@ -0,0 +1,290 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 4.05, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.WQ.s_diff", + "type": "number", + "value": 5.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.WBS.s_diff", + "type": "number", + "value": 5.64, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C195.SLQ.rci", + "type": "number", + "value": 3.21, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C195.SLQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C195.WQ.rci", + "type": "number", + "value": -3.49, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C195.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C195.WBS.rci", + "type": "number", + "value": -2.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C195.WBS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C267.SLQ.rci", + "type": "number", + "value": 1.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C267.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C267.WQ.rci", + "type": "number", + "value": 2.57, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C267.WQ.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C267.WBS.rci", + "type": "number", + "value": 1.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C267.WBS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C277.WQ.rci", + "type": "number", + "value": -2.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C277.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C277.WBS.rci", + "type": "number", + "value": -2.84, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C277.WBS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C293.SLQ.rci", + "type": "number", + "value": -2.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C293.SLQ.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C293.WQ.rci", + "type": "number", + "value": -4.41, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C293.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C293.WBS.rci", + "type": "number", + "value": 4.26, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C293.WBS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C381.SLQ.rci", + "type": "number", + "value": -2.96, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C381.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C381.WQ.rci", + "type": "number", + "value": -2.94, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C381.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C382.SLQ.rci", + "type": "number", + "value": -1.24, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C382.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C382.WQ.rci", + "type": "number", + "value": -3.67, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C382.WQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C382.WBS.rci", + "type": "number", + "value": 3.9, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C382.WBS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C195:WQ", + "C277:WQ", + "C293:WBS", + "C293:WQ", + "C381:SLQ", + "C381:WQ", + "C382:WBS", + "C382:WQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C195:SLQ", + "C195:WBS", + "C267:WQ", + "C277:WBS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C277:SLQ", + "C381:WBS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.SLQ.recovered_pct", + "type": "number", + "value": 20.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.WQ.recovered_pct", + "type": "number", + "value": 83.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.WBS.recovered_pct", + "type": "number", + "value": 40.0, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0058/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0058/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0070/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..9ab24dad64ea22cb35fcf59a411aaf0d59fb4cb8 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +MI,Mood Inventory,9,0-36,5.2,0.86,16,higher_is_worse +WBS,Wellbeing Scale,16,0-50,6.0,0.86,22,higher_is_better +DFS,Daily Functioning Scale,15,0-60,6.9,0.92,27,higher_is_better +SC,Stress Checklist,10,0-40,7.6,0.82,20,higher_is_worse diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..3ae8f8667a733461135a119881cd684078d72d47 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C346,WBS,31,44,15,T1 +C174,MI,20,12,9,T1 +C174,WBS,13,22,10,T1 +C173,WBS,33,46,20,T2 +C173,MI,21,14,8,T1 +C143,SC,9,6,7,T3 +C231,MI,8,8,7,T3 +C143,WBS,7,8,12,T2 +C173,SC,24,4,20,T2 +C231,SC,21,6,6,T1 +C346,MI,29,31,17,T1 +C317,WBS,19,8,11,T1 +C346,SC,36,39,14,T3 +C231,WBS,15,3,17,T3 +C143,MI,24,,3,T2 +C174,SC,11,27,13,T1 +C317,MI,26,18,6,T3 +C317,SC,22,28,13,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3a498acad4f91a9880157c3d5c36e8634dcf42bc --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-t0070/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cae4d8306e3ce93f50bcdc837a396c82bc5cb411 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/tests/checks.json @@ -0,0 +1,297 @@ +[ + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 2.75, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.SC.s_diff", + "type": "number", + "value": 4.56, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.WBS.s_diff", + "type": "number", + "value": 3.17, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C143.SC.rci", + "type": "number", + "value": -0.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C143.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C143.WBS.rci", + "type": "number", + "value": 0.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C143.WBS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C173.MI.rci", + "type": "number", + "value": -2.54, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C173.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C173.SC.rci", + "type": "number", + "value": -4.39, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C173.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C173.WBS.rci", + "type": "number", + "value": 4.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C173.WBS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C174.MI.rci", + "type": "number", + "value": -2.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C174.SC.rci", + "type": "number", + "value": 3.51, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.SC.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C174.WBS.rci", + "type": "number", + "value": 2.83, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C174.WBS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C231.MI.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C231.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C231.SC.rci", + "type": "number", + "value": -3.29, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C231.SC.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C231.WBS.rci", + "type": "number", + "value": -3.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C231.WBS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C317.MI.rci", + "type": "number", + "value": -2.91, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C317.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C317.SC.rci", + "type": "number", + "value": 1.32, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C317.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C317.WBS.rci", + "type": "number", + "value": -3.46, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C317.WBS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C346.MI.rci", + "type": "number", + "value": 0.73, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C346.SC.rci", + "type": "number", + "value": 0.66, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.SC.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C346.WBS.rci", + "type": "number", + "value": 4.09, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C346.WBS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C173:MI", + "C173:SC", + "C174:MI", + "C231:SC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C174:SC", + "C231:WBS", + "C317:WBS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C143:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.MI.recovered_pct", + "type": "number", + "value": 40.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.SC.recovered_pct", + "type": "number", + "value": 33.3, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.WBS.recovered_pct", + "type": "number", + "value": 0.0, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0070/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0070/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0082/environment/Dockerfile b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/instruments.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/instruments.csv new file mode 100644 index 0000000000000000000000000000000000000000..906b9f3e9599be57c54642a9238ad9a1306ab830 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/instruments.csv @@ -0,0 +1,5 @@ +code,name,items,score_range,sd,reliability,clinical_cutoff,direction +MI,Mood Inventory,9,0-36,6.9,0.85,14,higher_is_worse +WBS,Wellbeing Scale,16,0-50,8.7,0.88,20,higher_is_better +SLQ,Sleep Problems Questionnaire,7,0-30,5.7,0.84,12,higher_is_worse +DFS,Daily Functioning Scale,15,0-60,7.0,0.87,24,higher_is_better diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/outcomes.csv b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/outcomes.csv new file mode 100644 index 0000000000000000000000000000000000000000..41bf2661b8863ee6d2177e750d8213019cce4498 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/outcomes.csv @@ -0,0 +1,19 @@ +client_id,instrument,pre_score,post_score,sessions,therapist +C275,MI,16,3,20,T1 +C215,DFS,3,17,15,T3 +C215,MI,29,16,8,T3 +C266,MI,17,3,7,T2 +C128,DFS,49,37,15,T1 +C198,MI,29,17,7,T2 +C266,DFS,54,49,20,T1 +C128,MI,30,,3,T2 +C367,SLQ,28,28,18,T3 +C275,DFS,20,29,19,T1 +C367,MI,29,31,14,T1 +C367,DFS,3,13,7,T1 +C215,SLQ,15,1,10,T1 +C198,DFS,12,7,7,T3 +C198,SLQ,13,16,17,T3 +C275,SLQ,16,8,17,T3 +C266,SLQ,27,26,6,T3 +C128,SLQ,14,2,18,T3 diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/rci_rules.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/rci_rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0b07152a22f4941bda26c087af286ae2c37af8b1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/environment/workdir/rci_rules.md @@ -0,0 +1,28 @@ +# Reliable and clinically significant change + +These rules follow Jacobson and Truax (1991). The instruments are invented for practice. + +## Reliable change index + +For one client on one instrument: + + S_diff = SD * sqrt(2) * sqrt(1 - r) + RCI = (post - pre) / S_diff + +`SD` is the instrument's standard deviation and `r` its reliability, both from `instruments.csv`. `pre` is the score before treatment and `post` the score after it. Keep the sign: the RCI is negative when the score went down. + +The change is **reliable** when the RCI is above 1.96 or below -1.96. Otherwise it is not reliable. + +## Clinical range + +The `direction` column of `instruments.csv` says how to read the scores. + +- `higher_is_worse`: a score at or above `clinical_cutoff` is in the clinical range; a score below it is not. A lower score after treatment is an improvement. +- `higher_is_better`: a score at or below `clinical_cutoff` is in the clinical range; a score above it is not. A higher score after treatment is an improvement. + +## Status + +- `recovered`: the change is reliable, it is an improvement, the pre score was in the clinical range and the post score is not. +- `improved`: the change is reliable and an improvement, but the client is not `recovered` (the pre score was already outside the clinical range, or the post score is still inside it). +- `unchanged`: the change is not reliable. +- `deteriorated`: the change is reliable and in the direction of getting worse. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/instruction.md b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c7a593e42804a21fc93a1b8ab3804dffa4fab12 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/instruction.md @@ -0,0 +1,17 @@ +# Outcome review: reliable change + +`outcomes.csv` holds pre-treatment and post-treatment scores for 6 clients on 3 instruments, in no particular order. `instruments.csv` gives each instrument's standard deviation, reliability and clinical cut-off. `rci_rules.md` gives the formula and the classification rules. Some clients left treatment early and have no post score on an instrument: give no result for those rows and list them in `no_post`. + +Write `answer.json` in this folder, a JSON object with: + +- `instruments`: an object keyed by instrument code, for every instrument that appears in `outcomes.csv`. Each value has + - `s_diff`: the standard error of the difference, 2 decimals. + - `recovered_pct`: the percentage of the clients with both a pre and a post score on this instrument whose status is `recovered`, 1 decimal. +- `results`: an object keyed by client id, then by instrument code. Each value has + - `rci`: the reliable change index, 2 decimals, with its sign. + - `status`: one of `recovered`, `improved`, `unchanged`, `deteriorated`. +- `recovered`: list of strings of the form `":"` for every result with status `recovered` (any order; an empty list if none). +- `deteriorated`: the same for status `deteriorated`. +- `no_post`: list of `":"` strings for the rows without a post score (any order). + +Numbers are accepted within one unit of the last decimal place asked for. diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/solution/oracle.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/solution/solve.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/task.toml b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f159125fbec95517b5d13ce547eadb9d320ca61 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "reliable-change", "isced-0313", "train"] +isced_f = "0313" +family = "reliable-change" +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/psychometrics/psychometrics-reliable-change-d3-t0082/tests/checks.json b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..74b73df9d14902aac51e50b5d2724e6cfb21bdf2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/tests/checks.json @@ -0,0 +1,297 @@ +[ + { + "path": "instruments.SLQ.s_diff", + "type": "number", + "value": 3.22, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.MI.s_diff", + "type": "number", + "value": 3.78, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "instruments.DFS.s_diff", + "type": "number", + "value": 3.57, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C128.SLQ.rci", + "type": "number", + "value": -3.72, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C128.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C128.DFS.rci", + "type": "number", + "value": -3.36, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C128.DFS.status", + "type": "str", + "value": "deteriorated", + "weight": 1.0 + }, + { + "path": "results.C198.SLQ.rci", + "type": "number", + "value": 0.93, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C198.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C198.MI.rci", + "type": "number", + "value": -3.18, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C198.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C198.DFS.rci", + "type": "number", + "value": -1.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C198.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C215.SLQ.rci", + "type": "number", + "value": -4.34, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C215.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C215.MI.rci", + "type": "number", + "value": -3.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C215.MI.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C215.DFS.rci", + "type": "number", + "value": 3.92, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C215.DFS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "results.C266.SLQ.rci", + "type": "number", + "value": -0.31, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C266.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C266.MI.rci", + "type": "number", + "value": -3.7, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C266.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C266.DFS.rci", + "type": "number", + "value": -1.4, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C266.DFS.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C275.SLQ.rci", + "type": "number", + "value": -2.48, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C275.SLQ.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C275.MI.rci", + "type": "number", + "value": -3.44, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C275.MI.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C275.DFS.rci", + "type": "number", + "value": 2.52, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C275.DFS.status", + "type": "str", + "value": "recovered", + "weight": 1.0 + }, + { + "path": "results.C367.SLQ.rci", + "type": "number", + "value": 0.0, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C367.SLQ.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C367.MI.rci", + "type": "number", + "value": 0.53, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C367.MI.status", + "type": "str", + "value": "unchanged", + "weight": 1.0 + }, + { + "path": "results.C367.DFS.rci", + "type": "number", + "value": 2.8, + "abs_tol": 0.01, + "weight": 1.0 + }, + { + "path": "results.C367.DFS.status", + "type": "str", + "value": "improved", + "weight": 1.0 + }, + { + "path": "recovered", + "type": "set", + "value": [ + "C128:SLQ", + "C215:SLQ", + "C266:MI", + "C275:DFS", + "C275:MI", + "C275:SLQ" + ], + "item": "str", + "weight": 2 + }, + { + "path": "deteriorated", + "type": "set", + "value": [ + "C128:DFS" + ], + "item": "str", + "weight": 2 + }, + { + "path": "no_post", + "type": "set", + "value": [ + "C128:MI" + ], + "item": "str", + "weight": 2 + }, + { + "path": "instruments.SLQ.recovered_pct", + "type": "number", + "value": 50.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.MI.recovered_pct", + "type": "number", + "value": 40.0, + "abs_tol": 0.1, + "weight": 1.0 + }, + { + "path": "instruments.DFS.recovered_pct", + "type": "number", + "value": 16.7, + "abs_tol": 0.1, + "weight": 1.0 + } +] diff --git a/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/tests/test.sh b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-reliable-change-d3-t0082/tests/verify.py b/tasks/psychometrics/psychometrics-reliable-change-d3-t0082/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-reliable-change-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/psychometrics/psychometrics-scoring-d1-e0003/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-e0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0003/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-e0003/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..3aec5e0ac022d114cd00370ebadea07e8e12f0d2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0003/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C284,2025-09-28,RS,2,2,0,2,2,1,1,1,2,3,1,0 +C103,2025-09-17,MN,2,1,0,2,3,0,2,2,2,2,1,1 +C135,2025-09-16,MN,1,0,0,2,3,0,0,3,2,0,1,1 +C217,2025-10-09,KL,2,1,3,1,1,3,3,1,2,3,1,2 +C381,2025-06-12,RS,3,1,1,2,2,2,1,1,2,1,0,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0003/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-e0003/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..449a1e66b8c6517ddadabaf6dd995b6aac7c8991 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0003/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Stress Checklist (SC-12): scoring manual + +The Stress Checklist is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 5, 8, 9. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Energy | ENE | 1, 2, 8, 9, 10, 11 | +| Tension | TEN | 3, 4, 5, 6, 7, 12 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 7 | +| mild | 8 to 14 | +| moderate | 15 to 21 | +| severe | 22 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0003/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-e0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e5e1c24a3b4d19622e83efc2c28437c8e0051c7a --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0003/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Stress Checklist + +`responses.csv` holds the item responses of 5 clients to the Stress Checklist, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0003/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-e0003/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0003/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0003/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-e0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0003/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0003/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-e0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c76ee08714353695e43a9de95d992d76093423d7 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0003/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "eval"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-e0003/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-e0003/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d1a1c06fb7d3dac06420b8dfa7527290d68d0f56 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0003/tests/checks.json @@ -0,0 +1,133 @@ +[ + { + "path": "clients.C103.subscales.ENE", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C103.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C103.total", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C103.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C135.subscales.ENE", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C135.subscales.TEN", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C135.total", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C135.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C217.subscales.ENE", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C217.subscales.TEN", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C217.total", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C217.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.ENE", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C284.total", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C284.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C381.subscales.ENE", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C381.subscales.TEN", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C381.total", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C381.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C217", + "C284", + "C381" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0003/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-e0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-e0003/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-e0003/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-e0015/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-e0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0015/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-e0015/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..e18e338c90c4ef0fd345d558de0149318a2e859f --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0015/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C158,2025-06-01,KL,1,1,3,2,1,2,2,2,0,1,1,2 +C375,2025-11-09,AB,2,2,2,0,3,2,0,2,1,2,1,2 +C264,2025-06-03,RS,2,0,2,2,2,1,1,3,0,2,1,0 +C359,2025-07-28,KL,3,2,1,2,2,3,1,0,2,2,1,2 +C211,2025-06-25,RS,0,1,1,2,1,1,2,3,2,2,1,0 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0015/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-e0015/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..9e09700a39dc3ca4647c239e82c9b545a4201e76 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0015/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Daily Strain Scale (DSS-12): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 3, 4, 8. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Sleep | SLP | 1, 2, 6, 7, 11, 12 | +| Concentration | CON | 3, 4, 5, 8, 9, 10 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 9 | +| mild | 10 to 14 | +| moderate | 15 to 23 | +| severe | 24 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0015/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-e0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8c2631b7247eecf5f2c0679517fb33ac89ab8b2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0015/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 5 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0015/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-e0015/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0015/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0015/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-e0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0015/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0015/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-e0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fe4ae48f0e9b2c4731225ec6f744b848e1bb5476 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "eval"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-e0015/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-e0015/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..42218d08b374d046cfea5726aa47f43aa018c17e --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-e0015/tests/checks.json @@ -0,0 +1,132 @@ +[ + { + "path": "clients.C158.subscales.SLP", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C158.subscales.CON", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C158.total", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C158.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.SLP", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.CON", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C211.total", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C211.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C264.subscales.SLP", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C264.subscales.CON", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C264.total", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C264.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C359.subscales.SLP", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C359.subscales.CON", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C359.total", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C359.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.SLP", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.CON", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C375.total", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "clients.C375.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C359", + "C375" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-e0015/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-e0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-e0015/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-e0015/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0003/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-t0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0003/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-t0003/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..655dfea10f18c6d797375f34dcabf19dc6c6ab94 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0003/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C252,2025-06-01,AB,3,2,2,0,1,2,0,2,2,0,3,1 +C308,2025-10-12,AB,3,2,0,3,3,0,3,3,3,0,3,3 +C115,2025-09-04,MN,1,0,2,1,1,3,1,0,1,3,0,0 +C237,2025-11-17,AB,2,2,0,2,2,1,3,3,2,0,3,2 +C254,2025-09-06,RS,2,0,0,0,1,2,2,2,1,3,2,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0003/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-t0003/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..b2001939e55c0b8a261b6e319c5fa53a585f69aa --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0003/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Stress Checklist (SC-12): scoring manual + +The Stress Checklist is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 3, 6, 10. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Tension | TEN | 3, 4, 6, 7, 8, 12 | +| Sleep | SLP | 1, 2, 5, 9, 10, 11 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 9 | +| mild | 10 to 14 | +| moderate | 15 to 23 | +| severe | 24 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0003/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-t0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e5e1c24a3b4d19622e83efc2c28437c8e0051c7a --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0003/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Stress Checklist + +`responses.csv` holds the item responses of 5 clients to the Stress Checklist, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0003/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-t0003/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0003/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0003/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0003/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0003/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-t0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..62f206ce4ea249a2b33b5360b713e2dc2092ef04 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0003/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-t0003/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-t0003/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..176e7a1315bfe9106e3a4591f438c984363f01ea --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0003/tests/checks.json @@ -0,0 +1,134 @@ +[ + { + "path": "clients.C115.subscales.TEN", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C115.subscales.SLP", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C115.total", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C115.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C237.subscales.TEN", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C237.subscales.SLP", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C237.total", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C237.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C252.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C252.subscales.SLP", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C252.total", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C252.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C254.subscales.TEN", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C254.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C254.total", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C254.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C308.subscales.TEN", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C308.subscales.SLP", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C308.total", + "type": "int", + "value": 35, + "weight": 1.0 + }, + { + "path": "clients.C308.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C237", + "C252", + "C254", + "C308" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0003/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0003/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-t0003/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0015/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-t0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0015/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-t0015/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..0a4c318f0bbe61c9844e5e7afd0a9a693a1674f0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0015/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C268,2025-11-10,RS,2,3,2,0,3,0,1,1,3,1,0,0 +C281,2025-10-04,KL,1,1,3,2,3,3,3,3,1,1,2,3 +C285,2025-07-13,MN,3,3,0,1,1,0,0,0,3,0,0,1 +C244,2025-10-21,AB,0,0,2,3,1,3,2,3,1,2,3,3 +C235,2025-11-15,AB,2,1,3,3,3,2,1,2,1,2,1,3 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0015/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-t0015/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..ff3a8c8618921f930eae9937c7a129aebc634435 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0015/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Worry Questionnaire (WQ-12): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 1, 2, 9. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Sleep | SLP | 1, 3, 5, 9, 11, 12 | +| Social withdrawal | SOC | 2, 4, 6, 7, 8, 10 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 7 | +| mild | 8 to 15 | +| moderate | 16 to 21 | +| severe | 22 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0015/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-t0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..053fcc58e19a2e4b66a427a5175140f8c4d6ef3b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0015/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 5 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0015/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-t0015/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0015/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0015/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0015/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0015/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-t0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..be8ab8a13ceb9abe0b90f62227e18edd122abcf6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-t0015/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-t0015/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8aecaa8a92199e0e5cea4730e0dc3062d7079c18 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0015/tests/checks.json @@ -0,0 +1,133 @@ +[ + { + "path": "clients.C235.subscales.SLP", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C235.subscales.SOC", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C235.total", + "type": "int", + "value": 25, + "weight": 1.0 + }, + { + "path": "clients.C235.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C244.subscales.SLP", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C244.subscales.SOC", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C244.total", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "clients.C244.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C268.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C268.subscales.SOC", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C268.total", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C268.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.SLP", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.SOC", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C281.total", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C281.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C285.subscales.SLP", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C285.subscales.SOC", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C285.total", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C285.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C235", + "C244", + "C281" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0015/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0015/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-t0015/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0027/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-t0027/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0027/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0027/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-t0027/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..120a5cd91e69d7e3b02a8bc126b6dcb7839373c9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0027/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C281,2025-07-24,MN,1,1,0,3,2,0,1,3,0,0,1,0 +C373,2025-10-12,RS,0,0,1,2,3,0,1,3,0,0,0,0 +C378,2025-10-25,KL,1,0,2,3,3,2,0,3,1,2,0,1 +C343,2025-08-19,AB,1,0,0,2,3,0,0,3,0,0,0,2 +C341,2025-06-12,KL,2,2,1,3,2,2,0,2,1,2,1,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0027/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-t0027/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..3ff4ffe5787dae76f613d2c6474665490fc69fef --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0027/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Worry Questionnaire (WQ-12): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 4, 5, 8. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Tension | TEN | 1, 4, 5, 7, 9, 11 | +| Low mood | LOW | 2, 3, 6, 8, 10, 12 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 7 | +| mild | 8 to 15 | +| moderate | 16 to 23 | +| severe | 24 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0027/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-t0027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..053fcc58e19a2e4b66a427a5175140f8c4d6ef3b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0027/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 5 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0027/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-t0027/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0027/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0027/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0027/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0027/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0027/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-t0027/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d3870921a5b982bdb16dbccd067da71516c9f030 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0027/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-t0027/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-t0027/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..32304eeda0e599ef7bcd1371f298ea1adb03ad8e --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0027/tests/checks.json @@ -0,0 +1,129 @@ +[ + { + "path": "clients.C281.subscales.TEN", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.LOW", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C281.total", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C281.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C341.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C341.subscales.LOW", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C341.total", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C341.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C343.subscales.TEN", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C343.subscales.LOW", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C343.total", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C343.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C373.subscales.TEN", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C373.subscales.LOW", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C373.total", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C373.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C378.subscales.TEN", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C378.subscales.LOW", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C378.total", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C378.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0027/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0027/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0027/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-t0027/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0039/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-t0039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0039/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0039/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-t0039/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..5aebd143765af53535a2646e8f04a2fb7d3ddee8 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0039/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C113,2025-07-25,KL,2,3,3,3,3,1,3,0,2,0,3,1 +C297,2025-07-23,MN,3,3,2,2,1,2,2,1,2,1,2,1 +C374,2025-06-11,AB,2,2,1,0,2,1,2,2,1,1,1,2 +C212,2025-11-22,MN,0,1,0,1,0,1,0,3,0,3,0,2 +C116,2025-07-09,MN,2,2,3,1,1,1,2,2,2,2,1,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0039/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-t0039/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..cb52085302b77ef3bc37e97671e4a326f1a7c778 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0039/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Daily Strain Scale (DSS-12): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 8, 10, 12. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Energy | ENE | 1, 3, 4, 9, 10, 11 | +| Concentration | CON | 2, 5, 6, 7, 8, 12 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 9 | +| mild | 10 to 16 | +| moderate | 17 to 23 | +| severe | 24 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0039/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-t0039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8c2631b7247eecf5f2c0679517fb33ac89ab8b2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0039/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 5 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0039/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-t0039/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0039/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0039/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0039/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0039/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-t0039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..32f849630811d8b0eb8e02b08c2d3eba13162c4d --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0039/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-t0039/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-t0039/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..18b0dc14cfc46c317bf3de6cf99b74831070852b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0039/tests/checks.json @@ -0,0 +1,133 @@ +[ + { + "path": "clients.C113.subscales.ENE", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C113.subscales.CON", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C113.total", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "clients.C113.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C116.subscales.ENE", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C116.subscales.CON", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C116.total", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C116.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C212.subscales.ENE", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C212.subscales.CON", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C212.total", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C212.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C297.subscales.ENE", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C297.subscales.CON", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C297.total", + "type": "int", + "value": 25, + "weight": 1.0 + }, + { + "path": "clients.C297.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C374.subscales.ENE", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C374.subscales.CON", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C374.total", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C374.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C113", + "C116", + "C297" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0039/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0039/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-t0039/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0051/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-t0051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0051/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0051/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-t0051/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..20f27bb2b3c21d172e816a46fa4c57f1c5709ae3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0051/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C229,2025-07-01,KL,0,2,3,3,0,3,1,3,1,3,1,2 +C289,2025-06-21,KL,2,1,2,2,2,2,0,1,2,1,1,2 +C308,2025-10-10,RS,3,2,0,1,3,1,0,1,1,0,0,1 +C330,2025-07-28,RS,3,0,0,1,2,0,3,0,2,0,0,1 +C350,2025-06-16,AB,1,2,2,3,1,1,0,3,1,3,2,3 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0051/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-t0051/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..914a7ce50b16a71f5b80e310b5e5fe15e2fa9726 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0051/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Daily Strain Scale (DSS-12): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 1, 5, 9. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Sleep | SLP | 2, 6, 7, 8, 10, 11 | +| Concentration | CON | 1, 3, 4, 5, 9, 12 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 8 | +| mild | 9 to 15 | +| moderate | 16 to 23 | +| severe | 24 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0051/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-t0051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8c2631b7247eecf5f2c0679517fb33ac89ab8b2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0051/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 5 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0051/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-t0051/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0051/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0051/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0051/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0051/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0051/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-t0051/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..77d6d18f80405e2b0f368a7de8de5c798ea183bb --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0051/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-t0051/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-t0051/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..62140535745a4b447fe41fa1ca656679064550ac --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0051/tests/checks.json @@ -0,0 +1,132 @@ +[ + { + "path": "clients.C229.subscales.SLP", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C229.subscales.CON", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C229.total", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C229.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C289.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C289.subscales.CON", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C289.total", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C289.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C308.subscales.SLP", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C308.subscales.CON", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C308.total", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C308.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C330.subscales.SLP", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C330.subscales.CON", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C330.total", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C330.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C350.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C350.subscales.CON", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C350.total", + "type": "int", + "value": 25, + "weight": 1.0 + }, + { + "path": "clients.C350.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C229", + "C350" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0051/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0051/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0051/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-t0051/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0063/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0063/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0063/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-t0063/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..a8bd84e771b784790746a2691ed1cae713043fa1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0063/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C312,2025-07-08,MN,1,1,2,2,0,3,0,1,2,2,0,2 +C120,2025-09-02,MN,1,3,2,1,1,1,1,1,1,3,1,1 +C288,2025-11-11,AB,0,0,0,1,0,2,1,0,3,1,0,3 +C161,2025-08-02,KL,0,2,2,1,0,2,1,1,1,1,1,3 +C376,2025-11-06,AB,1,0,2,1,0,1,2,0,3,1,1,1 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0063/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-t0063/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..1fab31c72f9c7dfe6ee1f6852ea6e2b1ee62b3fa --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0063/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Mood Inventory (MI-12): scoring manual + +The Mood Inventory is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 6, 9, 12. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Energy | ENE | 1, 3, 5, 6, 7, 8 | +| Tension | TEN | 2, 4, 9, 10, 11, 12 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 9 | +| mild | 10 to 14 | +| moderate | 15 to 22 | +| severe | 23 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0063/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-t0063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ed3d1df0158db3cc3092bab75afbae64d0b28116 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0063/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Mood Inventory + +`responses.csv` holds the item responses of 5 clients to the Mood Inventory, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0063/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-t0063/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0063/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0063/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0063/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0063/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-t0063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0a43a9ea81e1ff5b70c963c28ed14ee3205dfca0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0063/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-t0063/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-t0063/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..c338fbf60d02c7fd733282f84d3a5f1cf7c90732 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0063/tests/checks.json @@ -0,0 +1,131 @@ +[ + { + "path": "clients.C120.subscales.ENE", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C120.subscales.TEN", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C120.total", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "clients.C120.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C161.subscales.ENE", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C161.subscales.TEN", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C161.total", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C161.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C288.subscales.ENE", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C288.subscales.TEN", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C288.total", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C288.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C312.subscales.ENE", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C312.subscales.TEN", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C312.total", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C312.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C376.subscales.ENE", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C376.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C376.total", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C376.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C120" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0063/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0063/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-t0063/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0075/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d1-t0075/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0075/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0075/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d1-t0075/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..fd4b4543abfe03c34c1f9be2baa2a85ff6fc969d --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0075/environment/workdir/responses.csv @@ -0,0 +1,6 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12 +C292,2025-07-09,KL,0,2,0,1,1,1,1,3,2,1,1,0 +C115,2025-08-01,RS,1,0,1,2,2,1,1,0,2,2,1,0 +C118,2025-10-09,MN,1,1,1,2,1,2,2,2,2,3,2,1 +C339,2025-07-25,KL,2,1,3,3,3,3,2,2,1,0,1,2 +C319,2025-06-23,KL,2,2,2,2,2,2,3,2,3,0,1,3 diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0075/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d1-t0075/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..fdce5e4553c12e38b27ee1dbce6f9a00ff07970d --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0075/environment/workdir/scoring_manual.md @@ -0,0 +1,30 @@ +# Daily Strain Scale (DSS-12): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 12 items, numbered 1 to 12. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 2, 10, 11. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Sleep | SLP | 1, 5, 7, 8, 10, 12 | +| Energy | ENE | 2, 3, 4, 6, 9, 11 | + +A subscale score is the sum of the item scores of its items. + +## Total score and severity band + +The total score is the sum of the subscale scores. + +| Band | Total score | +|---|---| +| minimal | 0 to 8 | +| mild | 9 to 14 | +| moderate | 15 to 22 | +| severe | 23 to 36 | diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0075/instruction.md b/tasks/psychometrics/psychometrics-scoring-d1-t0075/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8c2631b7247eecf5f2c0679517fb33ac89ab8b2 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0075/instruction.md @@ -0,0 +1,11 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 5 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. + - `total`: the total score, an integer. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0075/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d1-t0075/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0075/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0075/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0075/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0075/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0075/task.toml b/tasks/psychometrics/psychometrics-scoring-d1-t0075/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..39ffb8844cc4d7bb8cea528f084241af70befc00 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0075/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d1-t0075/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d1-t0075/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..8f38656b37b5ced42e2fc43a26a75e824765372d --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d1-t0075/tests/checks.json @@ -0,0 +1,134 @@ +[ + { + "path": "clients.C115.subscales.SLP", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C115.subscales.ENE", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C115.total", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C115.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C118.subscales.SLP", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C118.subscales.ENE", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C118.total", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C118.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C292.subscales.SLP", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C292.subscales.ENE", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C292.total", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C292.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C319.subscales.SLP", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C319.subscales.ENE", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C319.total", + "type": "int", + "value": 27, + "weight": 1.0 + }, + { + "path": "clients.C319.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C339.subscales.SLP", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C339.subscales.ENE", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C339.total", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C339.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C115", + "C118", + "C319", + "C339" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d1-t0075/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d1-t0075/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d1-t0075/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d1-t0075/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-e0007/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-e0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0007/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-e0007/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..2c276a2838826203beaae02cd008c0bf6944971b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0007/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C232,2025-09-09,RS,1,2,2,2,1,1,1,,0,2,0,2,2,2,1,0,1,3,3,2 +C313,2025-11-02,RS,2,1,1,1,,0,3,2,1,1,3,3,2,1,2,1,1,2,3,1 +C311,2025-10-17,RS,2,2,1,3,1,2,1,3,1,3,2,3,1,1,2,2,2,1,2, +C124,2025-09-16,KL,2,1,2,1,1,2,2,0,1,,1,1,3,2,1,0,1,2,3,1 +C396,2025-11-02,AB,2,,,1,0,1,,3,1,2,2,2,0,1,2,1,,1,3,2 +C388,2025-07-13,AB,3,,2,2,2,2,0,2,,0,3,2,2,1,3,2,3,2,0, +C253,2025-11-18,AB,3,1,2,3,3,2,0,1,2,1,2,3,2,1,3,3,3,3,1,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0007/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-e0007/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..33eea6ab4be61b35267a4f504e387d44a8d31814 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0007/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Daily Strain Scale (DSS-20): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 2, 7, 10, 14, 19. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Energy | ENE | 5, 6, 7, 8, 10, 12, 15, 16, 17, 20 | +| Sleep | SLP | 4, 11, 13, 14, 18 | +| Tension | TEN | 1, 2, 3, 9, 19 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 14 | +| mild | 15 to 26 | +| moderate | 27 to 39 | +| severe | 40 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0007/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-e0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..296e081b3bcfd426e6f87ddd74e122dd18de38ee --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0007/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 7 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0007/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-e0007/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0007/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0007/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-e0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0007/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0007/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-e0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7e4c7374433221adf954e43ba6c8d579e01ebfee --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "eval"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-e0007/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-e0007/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1c5d967b3073a5f688aff1d2a1c4745c8da5fb8a --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0007/tests/checks.json @@ -0,0 +1,197 @@ +[ + { + "path": "clients.C124.subscales.ENE", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C124.subscales.SLP", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C124.subscales.TEN", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C124.total", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C124.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C232.subscales.ENE", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C232.subscales.SLP", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C232.subscales.TEN", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C232.total", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C232.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C253.subscales.ENE", + "type": "int", + "value": 25, + "weight": 1.0 + }, + { + "path": "clients.C253.subscales.SLP", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C253.subscales.TEN", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C253.total", + "type": "int", + "value": 48, + "weight": 1.0 + }, + { + "path": "clients.C253.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C311.subscales.ENE", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C311.subscales.SLP", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C311.subscales.TEN", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C311.total", + "type": "int", + "value": 34, + "weight": 1.0 + }, + { + "path": "clients.C311.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C313.subscales.ENE", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C313.subscales.SLP", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C313.subscales.TEN", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C313.total", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C313.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C388.subscales.ENE", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C388.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C396.subscales.ENE", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C396.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C253", + "C311", + "C313" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C388:TEN", + "C396:TEN" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0007/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-e0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-e0007/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-e0007/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-e0019/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-e0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0019/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-e0019/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..1e2fd83f33f233b55e2dee293af08b63916daf4b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0019/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C373,2025-06-07,MN,1,0,1,2,1,0,1,2,2,1,1,3,2,1,1,1,3,1,1,2 +C354,2025-08-21,KL,2,2,0,1,2,1,1,0,0,1,2,0,0,2,2,1,2,1,1,0 +C368,2025-09-01,KL,0,1,0,0,2,,2,3,2,3,1,1,3,1,1,3,0,1,2,1 +C200,2025-10-05,AB,2,3,1,2,0,0,0,0,0,0,0,0,1,3,0,1,2,0,0,0 +C231,2025-11-07,MN,1,0,,0,,2,2,3,3,3,3,2,3,1,2,2,0,2,3,1 +C386,2025-11-28,RS,0,2,2,0,,0,1,1,1,1,2,2,2,1,1,3,2,2,,1 +C212,2025-09-05,RS,2,3,1,3,0,1,1,0,1,0,0,2,1,3,1,1,,0,0,1 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0019/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-e0019/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..3ac1b517d8edbb5ac9458a37cbbacd835a953a16 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0019/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Daily Strain Scale (DSS-20): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 1, 2, 4, 14, 17. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Low mood | LOW | 4, 8, 11, 18, 19 | +| Energy | ENE | 2, 3, 5, 6, 7, 9, 12, 20 | +| Tension | TEN | 1, 10, 13, 14, 15, 16, 17 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 13 | +| mild | 14 to 25 | +| moderate | 26 to 37 | +| severe | 38 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0019/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-e0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..296e081b3bcfd426e6f87ddd74e122dd18de38ee --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0019/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 7 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0019/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-e0019/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0019/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0019/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-e0019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0019/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0019/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-e0019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..42f60a5b1ba7126bc8b277bebb84c48fa2815875 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0019/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "eval"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-e0019/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-e0019/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..ec93c083a2579072baaf4c1f4caf51ba2e8a57f9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-e0019/tests/checks.json @@ -0,0 +1,214 @@ +[ + { + "path": "clients.C200.subscales.LOW", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C200.subscales.ENE", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C200.subscales.TEN", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C200.total", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C200.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C212.subscales.LOW", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "clients.C212.subscales.ENE", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C212.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C212.total", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C212.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C231.subscales.LOW", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C231.subscales.TEN", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C354.subscales.LOW", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C354.subscales.ENE", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C354.subscales.TEN", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C354.total", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C354.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C368.subscales.LOW", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C368.subscales.ENE", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C368.subscales.TEN", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C368.total", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "clients.C368.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C373.subscales.LOW", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C373.subscales.ENE", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C373.subscales.TEN", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C373.total", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C373.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C386.subscales.LOW", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C386.subscales.ENE", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C386.subscales.TEN", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C386.total", + "type": "int", + "value": 32, + "weight": 1.0 + }, + { + "path": "clients.C386.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C368", + "C373", + "C386" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C231:ENE" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-e0019/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-e0019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-e0019/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-e0019/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0007/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-t0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0007/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-t0007/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..6e70804d9037492c6b283ea03941bf28f660cdcf --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0007/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C361,2025-07-21,RS,,2,3,3,1,,1,2,1,2,0,2,0,,3,,2,0,2,2 +C238,2025-10-05,MN,0,3,1,2,1,0,0,1,2,1,0,2,1,3,3,0,3,,2,0 +C378,2025-11-08,RS,2,0,2,2,1,,1,1,2,1,2,0,2,0,0,0,0,2,1,3 +C394,2025-11-20,AB,3,2,2,0,3,1,2,1,1,2,2,3,1,1,2,1,2,0,1,1 +C209,2025-10-06,KL,3,1,1,1,0,0,0,0,0,1,3,1,3,1,0,1,0,3,0,1 +C284,2025-07-12,RS,2,2,2,3,2,2,2,2,3,1,1,1,1,2,3,1,2,1,2,1 +C121,2025-06-19,MN,3,2,2,1,1,2,1,2,0,3,0,1,2,1,2,1,,1,1,1 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0007/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-t0007/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..5639a47815921299dad7a8df84c706fc033675b4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0007/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Daily Strain Scale (DSS-20): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 1, 11, 13, 18, 20. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Energy | ENE | 10, 12, 14, 16, 17, 18, 20 | +| Concentration | CON | 1, 2, 4, 5, 7 | +| Low mood | LOW | 3, 6, 8, 9, 11, 13, 15, 19 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 13 | +| mild | 14 to 26 | +| moderate | 27 to 37 | +| severe | 38 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0007/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-t0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..296e081b3bcfd426e6f87ddd74e122dd18de38ee --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0007/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 7 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0007/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-t0007/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0007/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0007/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0007/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0007/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-t0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2927cdba25148be07e5b1b2886ec6a2af544669b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-t0007/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-t0007/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cd439263613d2ae3cc7b6f8d34349d9ad99e24b9 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0007/tests/checks.json @@ -0,0 +1,215 @@ +[ + { + "path": "clients.C121.subscales.ENE", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C121.subscales.CON", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C121.subscales.LOW", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C121.total", + "type": "int", + "value": 30, + "weight": 1.0 + }, + { + "path": "clients.C121.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C209.subscales.ENE", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C209.subscales.CON", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C209.subscales.LOW", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C209.total", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C209.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C238.subscales.ENE", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C238.subscales.CON", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C238.subscales.LOW", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C238.total", + "type": "int", + "value": 37, + "weight": 1.0 + }, + { + "path": "clients.C238.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.ENE", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.CON", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.LOW", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C284.total", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "clients.C284.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C361.subscales.CON", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C361.subscales.LOW", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C378.subscales.ENE", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C378.subscales.CON", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C378.subscales.LOW", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C378.total", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C378.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C394.subscales.ENE", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C394.subscales.CON", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C394.subscales.LOW", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C394.total", + "type": "int", + "value": 32, + "weight": 1.0 + }, + { + "path": "clients.C394.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C121", + "C238", + "C284", + "C394" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C361:ENE" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0007/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0007/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-t0007/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0019/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-t0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0019/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-t0019/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..643663cf8551e92abf090df768b7b717c2e0a52b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0019/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C295,2025-07-25,KL,2,3,2,0,2,3,1,0,2,1,1,1,0,1,0,0,1,2,,3 +C296,2025-08-05,KL,2,2,2,1,2,2,2,1,2,2,1,1,1,2,3,3,1,0,2,1 +C165,2025-06-13,KL,2,2,2,1,2,2,3,1,1,2,1,3,1,2,1,1,1,1,3,3 +C322,2025-08-23,MN,0,0,3,3,1,0,0,2,0,1,1,1,2,1,3,3,1,1,1,1 +C216,2025-11-13,KL,2,1,1,0,2,3,1,2,3,2,,2,1,2,1,0,1,1,2,3 +C162,2025-10-17,AB,1,1,3,,1,0,0,,,1,0,0,3,2,3,1,1,,2,0 +C335,2025-11-09,RS,2,3,1,0,3,2,2,2,3,2,2,3,,2,0,1,2,3,2,3 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0019/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-t0019/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..a8f63b7891c49a83e9d3058db348bbdfbd021145 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0019/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Worry Questionnaire (WQ-20): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 3, 4, 13, 15, 16. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Tension | TEN | 1, 2, 3, 8, 9, 10, 12, 14, 17, 19 | +| Concentration | CON | 4, 5, 6, 7, 13, 20 | +| Sleep | SLP | 11, 15, 16, 18 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 15 | +| mild | 16 to 27 | +| moderate | 28 to 39 | +| severe | 40 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0019/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-t0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e9c6e209388e1703931f01a03abf3a4b28433eb --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0019/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 7 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0019/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-t0019/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0019/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0019/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0019/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0019/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-t0019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..149c7903b57029f23473e4d495e496cdda94de71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0019/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-t0019/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-t0019/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..d4cee6e69ae2a0d72a71daaf5d92455bcd857ce1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0019/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "clients.C162.subscales.TEN", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C162.subscales.CON", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C165.subscales.TEN", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C165.subscales.CON", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C165.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C165.total", + "type": "int", + "value": 38, + "weight": 1.0 + }, + { + "path": "clients.C165.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C216.subscales.TEN", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C216.subscales.CON", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C295.subscales.TEN", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C295.subscales.CON", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C295.subscales.SLP", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C295.total", + "type": "int", + "value": 37, + "weight": 1.0 + }, + { + "path": "clients.C295.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C296.subscales.TEN", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C296.subscales.CON", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C296.subscales.SLP", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C296.total", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C296.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C322.subscales.TEN", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C322.subscales.CON", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C322.subscales.SLP", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C322.total", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C322.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C335.subscales.TEN", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C335.subscales.CON", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C335.subscales.SLP", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C335.total", + "type": "int", + "value": 49, + "weight": 1.0 + }, + { + "path": "clients.C335.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C165", + "C295", + "C296", + "C335" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C162:SLP", + "C216:SLP" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0019/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0019/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-t0019/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0031/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-t0031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0031/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0031/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-t0031/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..829c77d49ae12dc9b08622018d9415db02a889b3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0031/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C281,2025-10-15,AB,1,1,3,3,1,3,0,2,0,2,0,1,0,0,0,3,1,2,0,0 +C243,2025-06-22,KL,2,2,1,,2,0,2,2,2,3,1,3,2,2,2,1,2,2,2,2 +C350,2025-06-05,MN,1,1,1,2,3,2,2,,3,0,,0,0,1,0,1,1,1,1,1 +C273,2025-11-16,MN,2,2,1,2,2,0,,2,3,2,1,3,2,2,2,1,2,3,3,3 +C118,2025-08-22,AB,0,1,2,2,0,2,2,1,1,0,0,0,1,0,0,2,1,2,1,1 +C213,2025-07-28,KL,2,2,1,3,2,3,2,1,3,0,2,1,1,0,2,1,1,1,1,2 +C156,2025-06-03,AB,1,1,2,2,1,2,3,2,1,1,1,1,2,,0,1,0,1,1,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0031/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-t0031/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..4a71a60654cb8ee612bc28b9cbd41887915ce1ae --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0031/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Worry Questionnaire (WQ-20): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 3, 4, 6, 7, 16. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Energy | ENE | 1, 2, 5, 6, 7, 8, 12, 16, 17, 20 | +| Low mood | LOW | 3, 11, 13, 15, 18, 19 | +| Concentration | CON | 4, 9, 10, 14 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 15 | +| mild | 16 to 26 | +| moderate | 27 to 37 | +| severe | 38 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0031/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-t0031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e9c6e209388e1703931f01a03abf3a4b28433eb --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0031/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 7 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0031/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-t0031/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0031/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0031/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0031/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0031/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-t0031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d76f46bac162e597de068679100d47580cb2565 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0031/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-t0031/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-t0031/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6d5132ffc1490a87f4e02b548b9cec65c234edb3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0031/tests/checks.json @@ -0,0 +1,195 @@ +[ + { + "path": "clients.C118.subscales.ENE", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C118.subscales.LOW", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C118.subscales.CON", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C118.total", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C118.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C156.subscales.ENE", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C156.subscales.LOW", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C213.subscales.ENE", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C213.subscales.LOW", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C213.subscales.CON", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C213.total", + "type": "int", + "value": 26, + "weight": 1.0 + }, + { + "path": "clients.C213.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C243.subscales.ENE", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C243.subscales.LOW", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C273.subscales.ENE", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C273.subscales.LOW", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C273.subscales.CON", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C273.total", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C273.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.ENE", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.LOW", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.CON", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C281.total", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C281.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C350.subscales.ENE", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C350.subscales.LOW", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C350.subscales.CON", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C350.total", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C350.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C273" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C156:CON", + "C243:CON" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0031/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0031/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-t0031/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0043/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-t0043/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0043/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0043/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-t0043/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..27e7ecf76cae3696c60353728ecd4335c6335e2d --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0043/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C383,2025-08-20,RS,3,3,2,2,2,0,,2,1,3,2,1,3,2,1,1,0,0,2, +C185,2025-06-25,KL,1,0,3,1,0,3,0,2,1,1,2,2,0,0,1,2,1,2,0,1 +C195,2025-10-04,RS,0,2,1,1,3,0,1,1,2,1,2,1,2,2,2,2,0,1,1,2 +C248,2025-11-09,KL,,1,0,3,3,1,2,3,2,1,2,2,,3,3,1,,0,3,2 +C398,2025-07-08,RS,3,2,1,2,3,1,2,2,1,3,2,1,3,1,3,0,0,1,2,2 +C129,2025-07-09,MN,2,0,2,0,1,2,1,2,1,2,0,0,,0,2,1,1,2,0,2 +C384,2025-06-06,AB,2,,3,,0,3,1,0,1,1,3,2,2,1,2,1,0,0,0,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0043/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-t0043/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..da98682dc083d2c51ef9eecceeaecc2d56a7a0fb --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0043/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Daily Strain Scale (DSS-20): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 3, 6, 16, 17, 18. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Energy | ENE | 1, 3, 4, 8, 9, 11, 13, 17 | +| Tension | TEN | 5, 6, 12, 14, 15, 16, 20 | +| Social withdrawal | SOC | 2, 7, 10, 18, 19 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 13 | +| mild | 14 to 27 | +| moderate | 28 to 37 | +| severe | 38 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0043/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-t0043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..296e081b3bcfd426e6f87ddd74e122dd18de38ee --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0043/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 7 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0043/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-t0043/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0043/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0043/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0043/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0043/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0043/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-t0043/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..14a8cd5ca315ef57c0c11c16eab74529b8d467eb --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0043/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-t0043/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-t0043/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..96e41adf2a4304a5729ec3184b581eff6afff220 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0043/tests/checks.json @@ -0,0 +1,215 @@ +[ + { + "path": "clients.C129.subscales.ENE", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C129.subscales.TEN", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C129.subscales.SOC", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C129.total", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C129.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C185.subscales.ENE", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C185.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C185.subscales.SOC", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C185.total", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C185.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C195.subscales.ENE", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C195.subscales.TEN", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C195.subscales.SOC", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C195.total", + "type": "int", + "value": 34, + "weight": 1.0 + }, + { + "path": "clients.C195.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C248.subscales.TEN", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C248.subscales.SOC", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C383.subscales.ENE", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C383.subscales.TEN", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C383.subscales.SOC", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C383.total", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C383.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C384.subscales.ENE", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C384.subscales.TEN", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C384.subscales.SOC", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C384.total", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C384.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C398.subscales.ENE", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C398.subscales.TEN", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C398.subscales.SOC", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C398.total", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C398.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C195", + "C383", + "C384", + "C398" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C248:ENE" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0043/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0043/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0043/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-t0043/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0055/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-t0055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0055/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0055/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-t0055/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..5a6f91501997d26c00e3fd1679620a97df02e06d --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0055/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C370,2025-11-09,RS,0,2,0,0,0,0,2,0,2,0,0,0,0,3,1,,0,0,1,1 +C292,2025-09-02,RS,1,0,2,2,1,0,2,2,2,2,2,3,0,1,2,2,2,3,3,1 +C141,2025-08-16,KL,0,,0,1,1,2,3,0,3,0,0,,0,3,0,3,0,1,1,0 +C221,2025-09-12,AB,1,2,0,2,1,1,1,0,3,2,1,1,2,2,1,2,1,2,2,2 +C231,2025-06-14,AB,3,1,,1,1,2,1,3,0,2,2,1,3,2,1,2,1,3,2,2 +C162,2025-09-10,KL,0,2,2,1,1,0,2,,2,1,1,2,1,2,1,1,2,1,1,0 +C140,2025-08-26,RS,0,2,1,0,0,0,2,0,3,0,0,0,0,2,0,1,2,0,0,0 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0055/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-t0055/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..0396cce217de44e635689871057cde4fbac81a97 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0055/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Mood Inventory (MI-20): scoring manual + +The Mood Inventory is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 2, 7, 9, 14, 16. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Tension | TEN | 1, 2, 4, 5, 10, 15, 16, 17, 18, 19 | +| Social withdrawal | SOC | 3, 7, 12, 13 | +| Low mood | LOW | 6, 8, 9, 11, 14, 20 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 14 | +| mild | 15 to 27 | +| moderate | 28 to 39 | +| severe | 40 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0055/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-t0055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96db178275db7e32093bccda0b57728962c309af --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0055/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Mood Inventory + +`responses.csv` holds the item responses of 7 clients to the Mood Inventory, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0055/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-t0055/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0055/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0055/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0055/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0055/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0055/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-t0055/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..770c877b0c5c47152fb2c84626251db9acfedc7e --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0055/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-t0055/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-t0055/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2027f6db989885fb86d13c78f74456002ab370cf --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0055/tests/checks.json @@ -0,0 +1,195 @@ +[ + { + "path": "clients.C140.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C140.subscales.SOC", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C140.subscales.LOW", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C140.total", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C140.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C141.subscales.TEN", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C141.subscales.LOW", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C162.subscales.TEN", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C162.subscales.SOC", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C162.subscales.LOW", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C162.total", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C162.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C221.subscales.TEN", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C221.subscales.SOC", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C221.subscales.LOW", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C221.total", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C221.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C231.subscales.TEN", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C231.subscales.LOW", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C292.subscales.TEN", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "clients.C292.subscales.SOC", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C292.subscales.LOW", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C292.total", + "type": "int", + "value": 34, + "weight": 1.0 + }, + { + "path": "clients.C292.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C370.subscales.TEN", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C370.subscales.SOC", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C370.subscales.LOW", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C370.total", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C370.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C292" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C141:SOC", + "C231:SOC" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0055/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0055/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0055/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-t0055/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0067/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-t0067/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0067/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0067/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-t0067/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..19c20b7a094bd0d6b8637a8ca4f4764f6a98c0dc --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0067/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C104,2025-11-14,MN,3,0,3,3,0,2,0,3,3,3,3,2,2,3,1,3,0,3,3,2 +C197,2025-10-21,MN,1,1,3,1,2,3,0,1,1,1,2,1,0,0,0,0,1,1,3,2 +C118,2025-10-27,AB,2,1,3,3,1,3,1,3,1,2,2,1,2,1,2,2,2,2,2,2 +C234,2025-08-24,KL,2,0,2,3,1,3,1,3,1,,3,3,2,3,,3,1,3,3,3 +C287,2025-11-03,AB,3,2,1,2,,3,0,3,3,2,3,3,1,2,0,3,0,2,2,2 +C173,2025-06-15,RS,2,3,0,0,1,1,1,1,0,1,1,0,2,1,3,0,,0,1,1 +C335,2025-07-02,MN,2,2,,0,2,1,1,1,1,1,1,3,0,0,3,2,1,0,,1 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0067/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-t0067/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..677147b4621d7f818a151c760ec76d801bb03ca1 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0067/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Daily Strain Scale (DSS-20): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 2, 5, 7, 15, 17. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Social withdrawal | SOC | 2, 4, 5, 9, 10, 12, 13, 14, 17, 18 | +| Sleep | SLP | 6, 8, 11, 16, 20 | +| Tension | TEN | 1, 3, 7, 15, 19 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 15 | +| mild | 16 to 25 | +| moderate | 26 to 38 | +| severe | 39 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0067/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-t0067/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..296e081b3bcfd426e6f87ddd74e122dd18de38ee --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0067/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 7 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0067/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-t0067/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0067/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0067/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0067/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0067/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0067/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-t0067/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7959cb7937562b77c9c5dab917f947f8b8e509e0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0067/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-t0067/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-t0067/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..1587cf212c225ca8734d99818c8257c688846b9c --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0067/tests/checks.json @@ -0,0 +1,216 @@ +[ + { + "path": "clients.C104.subscales.SOC", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C104.subscales.SLP", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C104.subscales.TEN", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C104.total", + "type": "int", + "value": 55, + "weight": 1.0 + }, + { + "path": "clients.C104.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C118.subscales.SOC", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C118.subscales.SLP", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C118.subscales.TEN", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C118.total", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "clients.C118.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C173.subscales.SOC", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C173.subscales.SLP", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C173.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C173.total", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C173.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C197.subscales.SOC", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C197.subscales.SLP", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C197.subscales.TEN", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C197.total", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "clients.C197.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C234.subscales.SOC", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C234.subscales.SLP", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C234.subscales.TEN", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C234.total", + "type": "int", + "value": 50, + "weight": 1.0 + }, + { + "path": "clients.C234.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C287.subscales.SOC", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C287.subscales.SLP", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C287.subscales.TEN", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C287.total", + "type": "int", + "value": 47, + "weight": 1.0 + }, + { + "path": "clients.C287.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C335.subscales.SOC", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C335.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C104", + "C118", + "C197", + "C234", + "C287" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C335:TEN" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0067/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0067/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0067/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-t0067/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0079/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d2-t0079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0079/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0079/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d2-t0079/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..9c331fb92a6e9db7371660bc1b9890d0e999b953 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0079/environment/workdir/responses.csv @@ -0,0 +1,8 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20 +C171,2025-10-26,AB,3,2,3,2,2,1,3,1,3,0,2,1,1,1,2,0,3,2,1,2 +C375,2025-09-05,RS,3,1,2,2,2,3,1,3,2,0,1,1,1,1,3,2,2,,3,0 +C189,2025-09-01,AB,2,3,3,1,3,2,3,2,2,0,2,,3,2,1,2,3,3,3,1 +C192,2025-06-12,MN,0,0,,1,0,,1,0,1,3,0,1,0,2,0,2,2,0,2,3 +C273,2025-10-12,AB,0,1,0,0,1,2,3,0,1,2,1,3,1,3,0,2,0,1,2,1 +C168,2025-09-23,RS,0,1,2,2,3,2,2,3,3,0,2,0,,2,2,1,0,3,1,1 +C268,2025-10-08,MN,1,1,0,0,0,2,,1,,,1,1,0,2,0,1,1,0,,3 diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0079/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d2-t0079/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..9086abaa300c9807d12422f00307379db14ef91a --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0079/environment/workdir/scoring_manual.md @@ -0,0 +1,40 @@ +# Worry Questionnaire (WQ-20): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 20 items, numbered 1 to 20. +Each item is answered on a scale from 0 to 3. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 10, 12, 14, 16, 20. + +For a reverse-keyed item the item score is 3 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Sleep | SLP | 1, 4, 5, 7, 9, 10, 12, 15, 16, 19 | +| Low mood | LOW | 3, 6, 11, 14, 17 | +| Tension | TEN | 2, 8, 13, 18, 20 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 13 | +| mild | 14 to 26 | +| moderate | 27 to 38 | +| severe | 39 to 60 | diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0079/instruction.md b/tasks/psychometrics/psychometrics-scoring-d2-t0079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e9c6e209388e1703931f01a03abf3a4b28433eb --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0079/instruction.md @@ -0,0 +1,12 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 7 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0079/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d2-t0079/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0079/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0079/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0079/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0079/task.toml b/tasks/psychometrics/psychometrics-scoring-d2-t0079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..974b8f5a6bcf4acd1d4c7b336a154fed3272f9ae --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0079/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d2-t0079/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d2-t0079/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5dd1f5fd4341eefdf828b952f59cc49bd696ee67 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d2-t0079/tests/checks.json @@ -0,0 +1,198 @@ +[ + { + "path": "clients.C168.subscales.SLP", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C168.subscales.LOW", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C168.subscales.TEN", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C168.total", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "clients.C168.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C171.subscales.SLP", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C171.subscales.LOW", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C171.subscales.TEN", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C171.total", + "type": "int", + "value": 42, + "weight": 1.0 + }, + { + "path": "clients.C171.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C189.subscales.SLP", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C189.subscales.LOW", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C189.subscales.TEN", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C189.total", + "type": "int", + "value": 45, + "weight": 1.0 + }, + { + "path": "clients.C189.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C192.subscales.SLP", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C192.subscales.TEN", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "clients.C268.subscales.LOW", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C268.subscales.TEN", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C273.subscales.SLP", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C273.subscales.LOW", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C273.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C273.total", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C273.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.SLP", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.LOW", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.TEN", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C375.total", + "type": "int", + "value": 42, + "weight": 1.0 + }, + { + "path": "clients.C375.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C168", + "C171", + "C189", + "C375" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C192:LOW", + "C268:SLP" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d2-t0079/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d2-t0079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d2-t0079/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d2-t0079/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-e0011/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-e0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0011/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-e0011/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..fb7a18dd1eb376d40ed9f5cbaf857b5fcfef6793 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0011/environment/workdir/responses.csv @@ -0,0 +1,10 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C157,2025-06-02,AB,2,4,1,0,4,3,3,0,4,3,3,3,3,,0,0,3,4,2,3,3,3,4,4 +C257,2025-03-21,RS,1,3,1,0,4,3,2,1,4,3,9,4,4,3,0,0,4,2,3,3,4,4,4,4 +C278,2025-10-28,RS,4,0,4,3,0,0,,3,0,0,1,0,0,9,2,2,9,1,2,9,0,0,3,1 +C299,2025-09-13,KL,0,2,1,,1,3,3,1,3,4,2,2,3,3,1,0,2,4,2,4,2,4,1,2 +C147,2025-11-17,KL,4,0,4,4,0,1,1,4,0,1,1,0,0,1,3,3,,1,0,0,0,2,0,1 +C173,2025-11-01,AB,3,2,3,2,0,1,1,2,0,0,0,2,2,0,4,3,9,1,2,3,1,0,2,1 +C211,2025-08-24,RS,2,2,1,1,1,3,3,1,3,2,3,,3,4,1,1,3,,2,3,3,3,2,3 +C278,2025-01-10,KL,1,4,0,1,3,4,3,0,2,,2,4,9,3,1,0,2,4,2,4,4,3,4,4 +C257,2025-06-08,MN,3,2,3,3,1,1,3,2,2,2,3,1,3,2,2,1,2,3,1,2,2,1,2,1 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0011/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-e0011/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..c6d9b4b97e79434e1b8d790c89eea12a1deba03f --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0011/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Worry Questionnaire (WQ-24): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 1, 3, 4, 8, 15, 16. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Tension | TEN | 4, 7, 8, 13, 19 | +| Low mood | LOW | 3, 14, 16, 22 | +| Energy | ENE | 1, 2, 6, 10, 11, 12, 15, 20, 21, 24 | +| Sleep | SLP | 5, 9, 17, 18, 23 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 24 | +| mild | 25 to 42 | +| moderate | 43 to 60 | +| severe | 61 to 96 | + +## Risk item + +Item 10 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0011/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-e0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5642d4cb2ae95380aeb1db007476ed369d13497 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0011/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 7 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0011/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-e0011/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0011/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0011/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-e0011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0011/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0011/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-e0011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e18e87e5442cd213e842ba78fc1d7fcf5b3a1719 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0011/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "eval"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-e0011/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-e0011/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..3f857f0040c4387a5c54d56dca3e1445a40f2338 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0011/tests/checks.json @@ -0,0 +1,251 @@ +[ + { + "path": "clients.C147.subscales.TEN", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C147.subscales.LOW", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C147.subscales.ENE", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C147.subscales.SLP", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C147.total", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C147.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C157.subscales.TEN", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C157.subscales.ENE", + "type": "int", + "value": 32, + "weight": 1.0 + }, + { + "path": "clients.C157.subscales.SLP", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C173.subscales.TEN", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C173.subscales.LOW", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C173.subscales.ENE", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C173.subscales.SLP", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C173.total", + "type": "int", + "value": 26, + "weight": 1.0 + }, + { + "path": "clients.C173.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.TEN", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.LOW", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.ENE", + "type": "int", + "value": 27, + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C211.total", + "type": "int", + "value": 65, + "weight": 1.0 + }, + { + "path": "clients.C211.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C257.subscales.TEN", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C257.subscales.LOW", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C257.subscales.ENE", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C257.subscales.SLP", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C257.total", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C257.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C278.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C278.subscales.ENE", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C278.subscales.SLP", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C299.subscales.TEN", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C299.subscales.LOW", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C299.subscales.ENE", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C299.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C299.total", + "type": "int", + "value": 67, + "weight": 1.0 + }, + { + "path": "clients.C299.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C211", + "C257", + "C299" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C157:LOW", + "C278:LOW" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C157", + "C211", + "C257", + "C299" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0011/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-e0011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-e0011/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-e0011/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-e0023/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-e0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0023/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-e0023/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..74b9691f2636dabc09e2c228eea389402743c669 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0023/environment/workdir/responses.csv @@ -0,0 +1,12 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C234,2025-06-20,KL,3,2,3,3,1,4,3,2,2,2,3,,2,4,2,2,2,2,,9,2,2,2,1 +C340,2025-08-19,MN,1,3,3,1,3,0,0,0,1,0,1,4,1,1,1,1,0,3,1,0,2,2,2,2 +C281,2025-03-20,AB,4,,2,3,0,3,4,3,3,3,4,1,3,4,3,3,,9,2,4,3,2,1,3 +C183,2025-11-24,AB,0,2,4,1,3,0,1,1,1,2,1,3,0,1,1,1,0,4,2,1,,2,4,1 +C340,2025-02-17,AB,1,4,1,1,3,1,1,1,1,1,1,4,0,0,0,1,1,3,0,0,2,1,3,2 +C178,2025-08-19,KL,4,1,1,2,1,4,3,2,1,1,3,2,2,2,4,2,2,2,3,2,4,2,1,3 +C270,2025-09-14,KL,1,1,1,2,3,2,1,2,1,3,1,2,9,9,2,3,1,2,0,2,1,1,2,2 +C234,2025-04-14,AB,4,1,0,4,2,3,2,2,3,4,4,1,4,3,2,3,4,2,4,2,3,3,0,4 +C270,2025-05-13,MN,2,2,2,2,2,3,3,2,1,2,1,4,2,2,3,3,3,1,2,,2,3,2,2 +C383,2025-11-04,RS,2,1,2,4,2,2,4,2,3,3,3,0,3,4,3,4,2,1,3,2,4,1,1,2 +C281,2025-11-27,AB,1,4,3,1,4,0,1,0,1,0,1,3,1,1,0,0,0,4,0,1,1,0,3,1 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0023/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-e0023/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..b1d43b7c413ede8cdebc490e172b86260d000156 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0023/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Daily Strain Scale (DSS-24): scoring manual + +The Daily Strain Scale is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 2, 3, 5, 12, 18, 23. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Low mood | LOW | 2, 9, 10, 11, 15, 17, 24 | +| Social withdrawal | SOC | 1, 4, 13, 22 | +| Sleep | SLP | 3, 7, 16, 18, 19, 23 | +| Concentration | CON | 5, 6, 8, 12, 14, 20, 21 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 23 | +| mild | 24 to 41 | +| moderate | 42 to 61 | +| severe | 62 to 96 | + +## Risk item + +Item 24 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0023/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-e0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2a5305c36d6488ef6660dc702a2351cf05a32f6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0023/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Daily Strain Scale + +`responses.csv` holds the item responses of 7 clients to the Daily Strain Scale, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0023/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-e0023/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0023/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0023/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-e0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0023/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0023/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-e0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ff88627500bc9c44b9195c221319b52fa94c7cd4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "eval"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-e0023/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-e0023/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..36963b157e1c3baf128c717bee5ef5ccaf790509 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-e0023/tests/checks.json @@ -0,0 +1,250 @@ +[ + { + "path": "clients.C178.subscales.LOW", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C178.subscales.SOC", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C178.subscales.SLP", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C178.subscales.CON", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C178.total", + "type": "int", + "value": 62, + "weight": 1.0 + }, + { + "path": "clients.C178.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C183.subscales.LOW", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C183.subscales.SOC", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C183.subscales.SLP", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C183.subscales.CON", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C183.total", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C183.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C234.subscales.LOW", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C234.subscales.SOC", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C234.subscales.SLP", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C270.subscales.LOW", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C270.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C270.subscales.CON", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.LOW", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.SOC", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.SLP", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C281.subscales.CON", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C281.total", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C281.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C340.subscales.LOW", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C340.subscales.SOC", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C340.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C340.subscales.CON", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C340.total", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C340.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C383.subscales.LOW", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C383.subscales.SOC", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C383.subscales.SLP", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C383.subscales.CON", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "clients.C383.total", + "type": "int", + "value": 68, + "weight": 1.0 + }, + { + "path": "clients.C383.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C178", + "C383" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C234:CON", + "C270:SOC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C178", + "C270", + "C340", + "C383" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-e0023/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-e0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-e0023/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-e0023/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0011/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-t0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0011/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-t0011/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..fe5e7593e745f15caf399e5680c00f479514b3ce --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0011/environment/workdir/responses.csv @@ -0,0 +1,11 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C240,2025-08-24,RS,4,3,4,4,1,3,3,4,1,1,3,4,3,3,2,1,2,1,1,4,4,2,4,3 +C284,2025-07-13,RS,4,3,3,3,0,2,4,4,1,0,4,3,4,2,4,1,3,1,0,3,4,4,4,3 +C122,2025-09-01,KL,3,2,1,3,2,2,3,1,3,1,2,1,3,2,3,1,9,1,1,3,3,1,3,3 +C397,2025-06-04,AB,3,3,3,2,0,4,4,3,0,2,1,2,2,3,2,0,9,1,2,4,3,,9, +C392,2025-09-02,MN,1,3,0,0,3,1,2,2,1,2,2,1,2,2,2,2,1,2,3,1,2,1,2,1 +C295,2025-01-14,RS,1,1,2,2,2,,0,1,2,3,2,0,0,1,0,3,1,3,2,1,2,2,2,1 +C295,2025-07-07,KL,4,3,4,2,1,3,4,3,1,9,4,3,3,3,2,0,3,1,0,3,3,2,4,3 +C397,2025-05-05,RS,2,3,3,0,2,1,3,1,2,2,3,3,2,3,3,3,3,1,2,3,,3,2,2 +C195,2025-08-16,KL,2,0,1,0,3,1,0,1,3,4,0,9,0,0,1,4,0,4,4,2,,1,0,0 +C195,2025-03-23,AB,1,0,1,1,3,2,1,0,4,3,2,0,1,2,1,2,2,3,2,2,0,1,2,9 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0011/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-t0011/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..519bdaaf29ff5ea6156a175d635078f0dee9360f --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0011/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Worry Questionnaire (WQ-24): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 5, 9, 10, 16, 18, 19. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Social withdrawal | SOC | 6, 7, 9, 13, 16, 17, 20, 23 | +| Concentration | CON | 3, 11, 15, 19, 21, 22 | +| Tension | TEN | 1, 4, 8, 12, 14 | +| Energy | ENE | 2, 5, 10, 18, 24 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 24 | +| mild | 25 to 43 | +| moderate | 44 to 62 | +| severe | 63 to 96 | + +## Risk item + +Item 8 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0011/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-t0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5642d4cb2ae95380aeb1db007476ed369d13497 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0011/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 7 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0011/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-t0011/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0011/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0011/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0011/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0011/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-t0011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..93ea028681605c124e84189635820bc1cf90207f --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0011/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-t0011/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-t0011/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..9a9f8c2df62d9f37024e820679d20787ff9a2960 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0011/tests/checks.json @@ -0,0 +1,270 @@ +[ + { + "path": "clients.C122.subscales.SOC", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.CON", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.TEN", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.ENE", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C122.total", + "type": "int", + "value": 57, + "weight": 1.0 + }, + { + "path": "clients.C122.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C195.subscales.SOC", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C195.subscales.CON", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C195.subscales.TEN", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C195.subscales.ENE", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C195.total", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C195.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C240.subscales.SOC", + "type": "int", + "value": 25, + "weight": 1.0 + }, + { + "path": "clients.C240.subscales.CON", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C240.subscales.TEN", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C240.subscales.ENE", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C240.total", + "type": "int", + "value": 77, + "weight": 1.0 + }, + { + "path": "clients.C240.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.SOC", + "type": "int", + "value": 26, + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.CON", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.TEN", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C284.subscales.ENE", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C284.total", + "type": "int", + "value": 82, + "weight": 1.0 + }, + { + "path": "clients.C284.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C295.subscales.SOC", + "type": "int", + "value": 27, + "weight": 1.0 + }, + { + "path": "clients.C295.subscales.CON", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C295.subscales.TEN", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C295.subscales.ENE", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C295.total", + "type": "int", + "value": 76, + "weight": 1.0 + }, + { + "path": "clients.C295.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C392.subscales.SOC", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C392.subscales.CON", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C392.subscales.TEN", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C392.subscales.ENE", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C392.total", + "type": "int", + "value": 37, + "weight": 1.0 + }, + { + "path": "clients.C392.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C397.subscales.CON", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C397.subscales.TEN", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C397.subscales.ENE", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C122", + "C240", + "C284", + "C295" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C397:SOC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C240", + "C284", + "C295", + "C392", + "C397" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0011/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0011/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-t0011/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0023/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-t0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0023/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-t0023/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..0eb3d67ac70b37297d010ed89e710bcee8ffcc5d --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0023/environment/workdir/responses.csv @@ -0,0 +1,14 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C224,2025-01-22,RS,2,1,2,1,2,1,2,0,1,1,1,2,1,4,3,1,1,1,2,3,2,4,3,0 +C211,2025-10-02,MN,2,,2,,3,2,1,2,3,2,2,3,3,9,9,3,1,1,1,2,1,2,3,3 +C209,2025-03-09,RS,0,1,0,1,0,2,0,2,1,1,0,1,1,4,3,0,0,1,3,3,1,2,3,0 +C315,2025-08-23,MN,2,3,1,1,2,3,0,,0,0,0,2,,2,2,2,2,2,3,1,2,2,3,2 +C144,2025-04-11,RS,4,3,3,2,4,3,2,4,3,2,3,3,3,0,0,4,3,4,1,0,3,0,1,4 +C314,2025-08-14,MN,3,1,1,2,2,0,0,1,2,,1,1,1,4,3,0,2,0,3,3,,3,4,0 +C224,2025-08-16,AB,2,1,1,2,1,2,2,2,1,1,1,0,1,2,3,2,4,,2,3,2,4,3,0 +C144,2025-06-26,RS,2,3,2,2,1,2,2,1,2,1,2,1,2,2,2,,4,3,3,2,2,2,2,1 +C303,2025-02-09,MN,2,9,3,2,2,4,2,3,1,2,3,0,1,2,0,2,1,9,2,2,1,2,2,3 +C303,2025-10-27,RS,3,2,1,2,3,4,,3,3,2,3,3,3,2,1,4,3,3,,2,2,2,2,4 +C211,2025-03-20,KL,1,1,0,0,0,1,1,1,1,1,1,2,0,4,3,0,0,1,,3,2,3,3,1 +C314,2025-01-15,MN,1,1,1,,,1,1,1,0,1,1,0,9,3,3,1,1,1,3,2,1,3,9,1 +C209,2025-07-16,RS,1,0,0,2,1,2,0,,2,0,2,1,1,3,4,0,1,1,,3,0,4,2,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0023/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-t0023/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..9bb438587da70e34ab0c1c6bef4fa28a1663347b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0023/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Stress Checklist (SC-24): scoring manual + +The Stress Checklist is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 14, 15, 19, 20, 22, 23. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Social withdrawal | SOC | 3, 4, 8, 16, 22, 24 | +| Sleep | SLP | 6, 13, 14, 17, 18 | +| Energy | ENE | 1, 2, 9, 11, 21 | +| Concentration | CON | 5, 7, 10, 12, 15, 19, 20, 23 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 23 | +| mild | 24 to 41 | +| moderate | 42 to 62 | +| severe | 63 to 96 | + +## Risk item + +Item 16 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0023/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-t0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31a3b350a05035543b82d71a9094ff6c26a5894b --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0023/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Stress Checklist + +`responses.csv` holds the item responses of 7 clients to the Stress Checklist, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0023/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-t0023/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0023/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0023/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0023/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0023/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-t0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3e94ee7ab6a941fd3874c266a0396ec5d578bcc8 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-t0023/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-t0023/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..5aa8f0f82bbf74d2bb4e2cc70ab23867a220aee0 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0023/tests/checks.json @@ -0,0 +1,267 @@ +[ + { + "path": "clients.C144.subscales.SOC", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C144.subscales.SLP", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C144.subscales.ENE", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C144.subscales.CON", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C144.total", + "type": "int", + "value": 46, + "weight": 1.0 + }, + { + "path": "clients.C144.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C209.subscales.SOC", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C209.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C209.subscales.ENE", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C209.subscales.CON", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C209.total", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C209.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.SOC", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.SLP", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.ENE", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C211.subscales.CON", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C211.total", + "type": "int", + "value": 50, + "weight": 1.0 + }, + { + "path": "clients.C211.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C224.subscales.SOC", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C224.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C224.subscales.ENE", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C224.subscales.CON", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C224.total", + "type": "int", + "value": 34, + "weight": 1.0 + }, + { + "path": "clients.C224.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C303.subscales.SOC", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C303.subscales.SLP", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C303.subscales.ENE", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C314.subscales.SOC", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C314.subscales.SLP", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C314.subscales.ENE", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C314.subscales.CON", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C314.total", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C314.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C315.subscales.SOC", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C315.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C315.subscales.ENE", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C315.subscales.CON", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C315.total", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "clients.C315.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C144", + "C211" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C303:CON" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C211", + "C224", + "C303", + "C315" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0023/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0023/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-t0023/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0035/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-t0035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0035/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0035/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-t0035/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..d85a9f50b194ad15aac6acba6144d8d21cb298a4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0035/environment/workdir/responses.csv @@ -0,0 +1,11 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C245,2025-10-06,RS,3,4,4,3,1,2,2,3,4,4,4,1,3,3,3,4,1,4,3,1,4,2,4,2 +C371,2025-07-18,RS,2,4,2,3,1,3,1,1,4,2,3,2,3,3,3,3,0,3,4,1,4,1,4,2 +C375,2025-10-07,RS,1,1,0,1,2,1,2,2,2,2,0,3,2,2,2,2,2,2,1,3,2,2,2,2 +C244,2025-06-06,MN,,3,3,3,1,2,2,4,4,2,2,2,3,2,3,3,0,4,4,0,2,0,2,4 +C244,2025-02-11,MN,3,3,4,3,2,4,2,4,3,4,3,2,4,4,3,3,0,4,4,0,4,0,3,2 +C352,2025-08-17,MN,2,1,2,1,2,2,3,1,2,1,2,2,2,,1,1,2,0,2,4,2,3,1,0 +C121,2025-06-27,RS,3,2,2,1,4,2,2,1,1,2,3,2,2,2,1,1,1,1,9,3,3,4,0,1 +C122,2025-03-07,KL,1,1,2,2,1,3,3,2,2,2,2,2,2,3,2,4,3,1,1,1,1,2,2,3 +C122,2025-08-18,AB,3,4,3,3,2,,2,2,2,2,3,2,1,2,1,2,2,3,3,3,3,3,3,3 +C352,2025-01-16,RS,4,2,3,3,2,3,0,2,3,3,2,0,4,3,4,3,2,3,4,1,3,0,4,4 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0035/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-t0035/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..cad1a26bdfeb42a27390572a79ff73bf71ec021e --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0035/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Mood Inventory (MI-24): scoring manual + +The Mood Inventory is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 5, 7, 12, 17, 20, 22. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Concentration | CON | 5, 9, 10, 11, 13, 20, 22 | +| Energy | ENE | 3, 6, 7, 8, 14, 19 | +| Low mood | LOW | 4, 15, 17, 18, 21, 23, 24 | +| Social withdrawal | SOC | 1, 2, 12, 16 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 24 | +| mild | 25 to 42 | +| moderate | 43 to 62 | +| severe | 63 to 96 | + +## Risk item + +Item 13 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0035/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-t0035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f801f68e1740ade770c24ed76bc829f4c3ec3050 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0035/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Mood Inventory + +`responses.csv` holds the item responses of 7 clients to the Mood Inventory, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0035/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-t0035/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0035/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0035/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0035/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0035/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0035/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-t0035/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f3803f5dbc3ad8aa8159bcf9b59cf6545c88819 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0035/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-t0035/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-t0035/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..10771126176b7d1bf1c01ae34883e5e4e42e732e --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0035/tests/checks.json @@ -0,0 +1,270 @@ +[ + { + "path": "clients.C121.subscales.CON", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C121.subscales.ENE", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C121.subscales.LOW", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C121.subscales.SOC", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C121.total", + "type": "int", + "value": 38, + "weight": 1.0 + }, + { + "path": "clients.C121.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.CON", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.ENE", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.LOW", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.SOC", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C122.total", + "type": "int", + "value": 55, + "weight": 1.0 + }, + { + "path": "clients.C122.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C244.subscales.CON", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C244.subscales.ENE", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C244.subscales.LOW", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C245.subscales.CON", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C245.subscales.ENE", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C245.subscales.LOW", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C245.subscales.SOC", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C245.total", + "type": "int", + "value": 77, + "weight": 1.0 + }, + { + "path": "clients.C245.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C352.subscales.CON", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C352.subscales.ENE", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C352.subscales.LOW", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C352.subscales.SOC", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C352.total", + "type": "int", + "value": 33, + "weight": 1.0 + }, + { + "path": "clients.C352.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C371.subscales.CON", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C371.subscales.ENE", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C371.subscales.LOW", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C371.subscales.SOC", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C371.total", + "type": "int", + "value": 71, + "weight": 1.0 + }, + { + "path": "clients.C371.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.CON", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.ENE", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.LOW", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C375.subscales.SOC", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C375.total", + "type": "int", + "value": 37, + "weight": 1.0 + }, + { + "path": "clients.C375.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C122", + "C245", + "C371" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C244:SOC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C121", + "C244", + "C245", + "C352", + "C371", + "C375" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0035/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0035/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0035/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-t0035/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0047/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-t0047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0047/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0047/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-t0047/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..f523c4993610b262a2b7e2cdf5304832251ae9bd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0047/environment/workdir/responses.csv @@ -0,0 +1,11 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C141,2025-02-21,KL,1,2,3,1,2,9,4,9,3,2,2,2,4,3,1,2,,0,,1,3,3,2,2 +C223,2025-09-09,MN,1,2,2,1,2,2,3,2,1,2,3,2,4,1,2,0,1,2,3,2,2,2,2,3 +C148,2025-07-07,MN,3,4,2,2,4,4,4,2,4,0,3,3,2,4,4,1,0,2,4,4,3,4,2,2 +C181,2025-09-19,AB,2,1,1,3,2,1,0,1,1,2,0,1,2,2,2,3,2,3,1,1,2,2,1,3 +C141,2025-08-03,KL,3,2,2,3,2,3,3,2,2,1,0,3,2,,1,,2,2,2,3,2,2,3,2 +C270,2025-08-25,KL,3,2,3,1,4,2,2,3,3,9,4,4,4,2,3,1,0,2,4,1,0,3,3,3 +C282,2025-11-11,KL,2,2,3,1,4,2,2,4,1,0,4,2,3,3,9,2,0,3,3,4,1,2,1,2 +C270,2025-01-07,KL,3,3,3,0,4,3,4,3,3,0,2,4,2,4,3,0,0,2,4,2,1,4,4,2 +C122,2025-08-23,AB,1,1,2,2,2,3,1,1,2,2,1,1,0,1,2,2,4,1,,2,1,,0,3 +C181,2025-03-14,AB,4,4,,1,4,4,3,4,2,0,3,4,3,3,4,0,1,2,4,4,0,2,1,4 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0047/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-t0047/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..e416116eb3a23355471a2b07afbf25c0391b1f7c --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0047/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Worry Questionnaire (WQ-24): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 4, 10, 16, 17, 18, 21. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Concentration | CON | 1, 11, 12, 20, 21, 23 | +| Social withdrawal | SOC | 7, 9, 10, 24 | +| Tension | TEN | 2, 3, 4, 5, 14, 18, 22 | +| Energy | ENE | 6, 8, 13, 15, 16, 17, 19 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 22 | +| mild | 23 to 43 | +| moderate | 44 to 62 | +| severe | 63 to 96 | + +## Risk item + +Item 6 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0047/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-t0047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5642d4cb2ae95380aeb1db007476ed369d13497 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0047/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 7 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0047/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-t0047/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0047/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0047/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0047/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0047/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-t0047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bf559b85d60ccb31c600e3ecc4ba98cf2a0c0d52 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0047/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-t0047/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-t0047/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..2f8969da4e54671ac4db9993f08a45275e0f3405 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0047/tests/checks.json @@ -0,0 +1,271 @@ +[ + { + "path": "clients.C122.subscales.CON", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.SOC", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.TEN", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C122.subscales.ENE", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C122.total", + "type": "int", + "value": 38, + "weight": 1.0 + }, + { + "path": "clients.C122.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C141.subscales.CON", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C141.subscales.SOC", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C141.subscales.TEN", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C141.subscales.ENE", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C141.total", + "type": "int", + "value": 51, + "weight": 1.0 + }, + { + "path": "clients.C141.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C148.subscales.CON", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C148.subscales.SOC", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C148.subscales.TEN", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C148.subscales.ENE", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C148.total", + "type": "int", + "value": 75, + "weight": 1.0 + }, + { + "path": "clients.C148.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C181.subscales.CON", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C181.subscales.SOC", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C181.subscales.TEN", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C181.subscales.ENE", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C181.total", + "type": "int", + "value": 33, + "weight": 1.0 + }, + { + "path": "clients.C181.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C223.subscales.CON", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C223.subscales.SOC", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C223.subscales.TEN", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C223.subscales.ENE", + "type": "int", + "value": 20, + "weight": 1.0 + }, + { + "path": "clients.C223.total", + "type": "int", + "value": 55, + "weight": 1.0 + }, + { + "path": "clients.C223.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C270.subscales.CON", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C270.subscales.TEN", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C270.subscales.ENE", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C282.subscales.CON", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C282.subscales.SOC", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C282.subscales.TEN", + "type": "int", + "value": 18, + "weight": 1.0 + }, + { + "path": "clients.C282.subscales.ENE", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C282.total", + "type": "int", + "value": 64, + "weight": 1.0 + }, + { + "path": "clients.C282.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C141", + "C148", + "C223", + "C282" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C270:SOC" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C122", + "C141", + "C148", + "C223", + "C270", + "C282" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0047/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0047/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-t0047/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0059/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-t0059/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0059/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0059/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-t0059/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..cb604d03591f86f1fc63d401ff1d63d2e2be1668 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0059/environment/workdir/responses.csv @@ -0,0 +1,10 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C376,2025-06-20,AB,1,0,4,1,0,1,0,4,0,0,1,1,0,1,1,0,3,1,2,3,1,0,3,4 +C351,2025-01-23,KL,4,4,1,4,3,2,4,0,4,3,4,3,4,4,9,4,1,2,4,0,4,2,1,2 +C104,2025-10-27,MN,3,1,4,1,1,1,1,4,1,2,2,0,2,1,1,0,4,1,1,4,0,2,2,4 +C345,2025-06-16,MN,2,2,2,3,3,2,2,2,3,1,1,,2,1,4,1,2,2,1,3,,2,1, +C379,2025-07-10,MN,1,0,3,1,1,1,9,4,0,0,0,0,0,0,0,1,4,1,1,4,0,1,3,4 +C389,2025-11-27,KL,3,3,2,2,2,2,4,2,3,2,3,4,3,3,4,3,0,4,4,1,9,4,1,1 +C389,2025-04-23,RS,1,2,3,2,1,0,3,3,0,1,1,1,0,3,0,1,4,0,1,2,1,0,1,4 +C142,2025-09-18,MN,3,3,1,3,3,2,2,0,1,3,2,2,2,1,2,1,1,2,2,1,2,2,2,2 +C351,2025-11-25,AB,2,0,3,1,,1,1,3,2,9,0,1,1,1,1,1,4,1,0,2,1,2,4,4 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0059/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-t0059/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..3dba9602b063e722601658f716812e9f37d4eaed --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0059/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Mood Inventory (MI-24): scoring manual + +The Mood Inventory is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 3, 8, 17, 20, 23, 24. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Tension | TEN | 1, 12, 14, 21, 24 | +| Low mood | LOW | 3, 4, 5, 9, 16 | +| Sleep | SLP | 2, 6, 7, 8, 15, 17, 18, 20, 22, 23 | +| Concentration | CON | 10, 11, 13, 19 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 23 | +| mild | 24 to 42 | +| moderate | 43 to 60 | +| severe | 61 to 96 | + +## Risk item + +Item 7 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0059/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-t0059/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f801f68e1740ade770c24ed76bc829f4c3ec3050 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0059/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Mood Inventory + +`responses.csv` holds the item responses of 7 clients to the Mood Inventory, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0059/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-t0059/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0059/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0059/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0059/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0059/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0059/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-t0059/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ecb8ddaa60ab33d260d35fcaab0e258732be38e4 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0059/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-t0059/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-t0059/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..fa2b9ebdf53ddc240029fdffc34459d1e492aa01 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0059/tests/checks.json @@ -0,0 +1,249 @@ +[ + { + "path": "clients.C104.subscales.TEN", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C104.subscales.LOW", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C104.subscales.SLP", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C104.subscales.CON", + "type": "int", + "value": 7, + "weight": 1.0 + }, + { + "path": "clients.C104.total", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C104.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C142.subscales.TEN", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C142.subscales.LOW", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C142.subscales.SLP", + "type": "int", + "value": 25, + "weight": 1.0 + }, + { + "path": "clients.C142.subscales.CON", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C142.total", + "type": "int", + "value": 55, + "weight": 1.0 + }, + { + "path": "clients.C142.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C345.subscales.LOW", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C345.subscales.SLP", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C345.subscales.CON", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C351.subscales.TEN", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C351.subscales.LOW", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C351.subscales.SLP", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C376.subscales.TEN", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C376.subscales.LOW", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C376.subscales.SLP", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C376.subscales.CON", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C376.total", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C376.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C379.subscales.TEN", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C379.subscales.LOW", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C379.subscales.SLP", + "type": "int", + "value": 4, + "weight": 1.0 + }, + { + "path": "clients.C379.subscales.CON", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C379.total", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C379.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C389.subscales.TEN", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C389.subscales.LOW", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C389.subscales.SLP", + "type": "int", + "value": 33, + "weight": 1.0 + }, + { + "path": "clients.C389.subscales.CON", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C389.total", + "type": "int", + "value": 73, + "weight": 1.0 + }, + { + "path": "clients.C389.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C142", + "C389" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C345:TEN", + "C351:CON" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C142", + "C345", + "C389" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0059/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0059/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0059/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-t0059/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0071/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-t0071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0071/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0071/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-t0071/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..d33afb7b5d8be6342c174eb4dc63212155a8ef03 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0071/environment/workdir/responses.csv @@ -0,0 +1,9 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C387,2025-11-07,RS,3,3,1,2,,2,1,3,1,4,2,4,2,4,2,4,4,2,1,2,2,3,1,4 +C247,2025-08-22,MN,4,3,2,1,3,,2,3,3,2,2,3,2,2,2,2,1,2,1,2,3,2,2, +C247,2025-04-09,AB,3,1,3,2,0,3,1,1,2,1,2,9,2,3,3,2,3,2,1,2,2,2,2,1 +C116,2025-07-17,RS,2,4,2,0,3,4,4,3,3,3,1,4,2,3,4,4,4,0,2,3,3,3,4,4 +C378,2025-06-09,AB,4,3,0,0,3,3,3,4,4,4,1,3,0,4,3,4,2,2,2,4,3,3,3, +C283,2025-07-04,AB,2,1,1,2,2,1,2,2,9,3,2,1,4,2,1,1,1,4,2,3,1,1,2,3 +C181,2025-11-26,KL,3,3,1,0,4,4,4,3,3,4,1,4,0,3,3,4,4,0,0,3,3,4,4,4 +C362,2025-10-06,AB,3,3,2,0,3,4,3,3,2,4,2,3,2,2,3,2,,2,2,3,3,3,,2 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0071/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-t0071/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..894fe7eeffb507d26e0fdd4a4852a7d8681b27d3 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0071/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Worry Questionnaire (WQ-24): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 3, 4, 11, 13, 18, 19. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Concentration | CON | 4, 10, 21, 24 | +| Low mood | LOW | 5, 8, 14, 17, 20 | +| Sleep | SLP | 1, 3, 11, 13, 16 | +| Energy | ENE | 2, 6, 7, 9, 12, 15, 18, 19, 22, 23 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 22 | +| mild | 23 to 43 | +| moderate | 44 to 60 | +| severe | 61 to 96 | + +## Risk item + +Item 22 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0071/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-t0071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5642d4cb2ae95380aeb1db007476ed369d13497 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0071/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 7 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0071/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-t0071/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0071/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0071/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0071/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0071/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0071/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-t0071/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f0afb504f7f3ca300ff35a1af2cd59e6ead5c54 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0071/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-t0071/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-t0071/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..30420d4a78f4561f009f1f74576fa42c2f0d0aec --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0071/tests/checks.json @@ -0,0 +1,254 @@ +[ + { + "path": "clients.C116.subscales.CON", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C116.subscales.LOW", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C116.subscales.SLP", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C116.subscales.ENE", + "type": "int", + "value": 36, + "weight": 1.0 + }, + { + "path": "clients.C116.total", + "type": "int", + "value": 79, + "weight": 1.0 + }, + { + "path": "clients.C116.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C181.subscales.CON", + "type": "int", + "value": 15, + "weight": 1.0 + }, + { + "path": "clients.C181.subscales.LOW", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C181.subscales.SLP", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C181.subscales.ENE", + "type": "int", + "value": 37, + "weight": 1.0 + }, + { + "path": "clients.C181.total", + "type": "int", + "value": 86, + "weight": 1.0 + }, + { + "path": "clients.C181.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C247.subscales.LOW", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C247.subscales.SLP", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C247.subscales.ENE", + "type": "int", + "value": 24, + "weight": 1.0 + }, + { + "path": "clients.C283.subscales.CON", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C283.subscales.LOW", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C283.subscales.SLP", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C283.subscales.ENE", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C283.total", + "type": "int", + "value": 39, + "weight": 1.0 + }, + { + "path": "clients.C283.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "clients.C362.subscales.CON", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C362.subscales.LOW", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C362.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C362.subscales.ENE", + "type": "int", + "value": 28, + "weight": 1.0 + }, + { + "path": "clients.C362.total", + "type": "int", + "value": 66, + "weight": 1.0 + }, + { + "path": "clients.C362.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C378.subscales.LOW", + "type": "int", + "value": 17, + "weight": 1.0 + }, + { + "path": "clients.C378.subscales.SLP", + "type": "int", + "value": 19, + "weight": 1.0 + }, + { + "path": "clients.C378.subscales.ENE", + "type": "int", + "value": 29, + "weight": 1.0 + }, + { + "path": "clients.C387.subscales.CON", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C387.subscales.LOW", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C387.subscales.SLP", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C387.subscales.ENE", + "type": "int", + "value": 22, + "weight": 1.0 + }, + { + "path": "clients.C387.total", + "type": "int", + "value": 64, + "weight": 1.0 + }, + { + "path": "clients.C387.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C116", + "C181", + "C362", + "C387" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C247:CON", + "C378:CON" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C116", + "C181", + "C247", + "C362", + "C378", + "C387" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0071/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0071/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0071/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-t0071/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0083/environment/Dockerfile b/tasks/psychometrics/psychometrics-scoring-d3-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2579fdacf261c4800d0280c0927cbaace75c6cd --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0083/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0083/environment/workdir/responses.csv b/tasks/psychometrics/psychometrics-scoring-d3-t0083/environment/workdir/responses.csv new file mode 100644 index 0000000000000000000000000000000000000000..ab72317f4fe3b603780aca54fa72578ba265c71a --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0083/environment/workdir/responses.csv @@ -0,0 +1,11 @@ +client_id,administered,clinician,item_01,item_02,item_03,item_04,item_05,item_06,item_07,item_08,item_09,item_10,item_11,item_12,item_13,item_14,item_15,item_16,item_17,item_18,item_19,item_20,item_21,item_22,item_23,item_24 +C344,2025-06-23,RS,0,1,1,4,4,0,0,2,2,4,0,1,0,0,4,0,0,0,0,0,1,4,1,0 +C255,2025-09-20,MN,0,2,3,1,2,2,2,1,2,3,2,2,1,2,4,,2,1,3,,2,1,2,2 +C268,2025-10-10,RS,0,2,2,4,3,1,9,1,9,2,2,1,0,0,3,0,3,9,0,1,1,9,1,2 +C309,2025-08-14,AB,2,2,2,2,1,4,2,2,2,1,2,3,2,1,,3,1,2,2,2,2,2,9,2 +C311,2025-03-06,AB,2,3,3,1,1,4,4,4,0,0,4,4,4,4,2,3,3,3,4,3,4,1,3,3 +C311,2025-07-27,AB,2,4,2,1,0,3,4,2,1,1,4,4,2,3,1,4,3,4,9,3,4,1,4,4 +C361,2025-07-18,AB,1,0,2,3,2,1,1,0,4,2,0,2,2,2,2,0,0,0,2,1,1,3,0,2 +C344,2025-03-14,RS,3,3,4,2,1,4,2,3,2,0,4,3,3,3,1,4,3,4,4,3,3,0,3,4 +C268,2025-04-10,RS,3,3,4,0,1,4,3,3,1,2,,4,3,9,2,4,3,4,1,3,3,1,2,4 +C246,2025-06-20,KL,2,3,2,1,0,4,,,2,1,3,3,4,1,1,3,3,3,4,3,3,1,2,3 diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0083/environment/workdir/scoring_manual.md b/tasks/psychometrics/psychometrics-scoring-d3-t0083/environment/workdir/scoring_manual.md new file mode 100644 index 0000000000000000000000000000000000000000..90dc528cd63e30bafe858e51456fca73bfea9be6 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0083/environment/workdir/scoring_manual.md @@ -0,0 +1,45 @@ +# Worry Questionnaire (WQ-24): scoring manual + +The Worry Questionnaire is an invented questionnaire used for practice. It has 24 items, numbered 1 to 24. +Each item is answered on a scale from 0 to 4. Higher scores mean more difficulties. + +## Reverse-keyed items + +Reverse-keyed items: 4, 5, 9, 10, 15, 22. + +For a reverse-keyed item the item score is 4 minus the response. For every other item the item score is the response. + +## Subscales + +| Subscale | Code | Items | +|---|---|---| +| Low mood | LOW | 9, 14, 15, 18, 22 | +| Concentration | CON | 1, 6, 13, 24 | +| Sleep | SLP | 3, 7, 10, 11, 17 | +| Social withdrawal | SOC | 2, 4, 5, 8, 12, 16, 19, 20, 21, 23 | + +A subscale score is the sum of the item scores of its items. + +## Missing responses + +An empty cell means the item was not answered. The code 9 also means the item was not answered. + +- If no item of a subscale is missing, the subscale score is the plain sum. +- If some items are missing, but at most 20% of the subscale's items, prorate: add up the item scores of the answered items, multiply by the number of items in the subscale, divide by the number of answered items, and round to a whole number (round half up). +- If more than 20% of the subscale's items are missing, the subscale is not scorable. +- If any subscale is not scorable, the total score and the severity band are not scorable either. + +## Total score and severity band + +The total score is the sum of the subscale scores (prorated scores where prorating was needed). + +| Band | Total score | +|---|---| +| minimal | 0 to 24 | +| mild | 25 to 42 | +| moderate | 43 to 60 | +| severe | 61 to 96 | + +## Risk item + +Item 24 is the risk item. Flag a client whose response to it, as answered, is 2 or more. A client who did not answer the risk item is not flagged. diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0083/instruction.md b/tasks/psychometrics/psychometrics-scoring-d3-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5642d4cb2ae95380aeb1db007476ed369d13497 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0083/instruction.md @@ -0,0 +1,13 @@ +# Questionnaire scoring: Worry Questionnaire + +`responses.csv` holds the item responses of 7 clients to the Worry Questionnaire, one row per administration, in no particular order. `scoring_manual.md` is the scoring manual: follow it exactly. Some clients filled in the questionnaire more than once: score only each client's most recent administration (the latest `administered` date). + +Write `answer.json` in this folder, a JSON object with: + +- `clients`: an object keyed by client id. Each value has + - `subscales`: an object keyed by subscale code, giving each subscale score as an integer. Leave out a subscale that is not scorable. + - `total`: the total score, an integer. Leave it out if it is not scorable. + - `band`: the severity band, one of `minimal`, `mild`, `moderate`, `severe`. Leave it out if the total is not scorable. +- `moderate_or_severe`: list of the client ids whose band is `moderate` or `severe` (any order; an empty list if none). +- `unscorable`: list of strings of the form `":"`, one for every subscale that is not scorable (any order; an empty list if none). +- `risk_flagged`: list of the client ids flagged on the risk item (any order; an empty list if none). diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0083/solution/oracle.py b/tasks/psychometrics/psychometrics-scoring-d3-t0083/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..a42c8eaee6418eabd1016cf7b6e80ed5d79bbe63 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0083/solution/oracle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Reference solution for Psychometrics. Works only from the files in the current directory.""" +import csv, json, math, os, re +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction + +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 nums(s): return [int(x) for x in re.findall(r"\d+", s)] + +# ---------------------------------------------------------------- scoring +def scoring(): + man = text("scoring_manual.md") + top = int(re.search(r"scale from 0 to (\d+)", man).group(1)) + reverse = set(nums(re.search(r"^Reverse-keyed items:(.*)$", man, re.M).group(1))) + subs, bands = [], [] + for line in man.splitlines(): + cells = [c.strip() for c in line.strip().strip("|").split("|")] + if len(cells) == 3 and re.match(r"^[A-Z]{3}$", cells[1]): subs.append((cells[1], nums(cells[2]))) + if len(cells) == 2 and re.match(r"^\d+ to \d+$", cells[1]): bands.append((cells[0], nums(cells[1]))) + missing_codes = {""} + if "code 9" in man: missing_codes.add("9") + m = re.search(r"Item (\d+) is the risk item", man) + risk = int(m.group(1)) if m else None + latest = {} + for r in rows("responses.csv"): + if r["client_id"] not in latest or r["administered"] > latest[r["client_id"]]["administered"]: latest[r["client_id"]] = r + ans = {"clients": {}, "moderate_or_severe": [], "unscorable": [], "risk_flagged": []} + for cid, r in latest.items(): + out = {"subscales": {}} + ok = True + for code, items in subs: + vals = [] + for i in items: + cell = r["item_%02d" % i].strip() + if cell in missing_codes: continue + v = int(cell) + vals.append(top - v if i in reverse else v) + n_miss = len(items) - len(vals) + if Fraction(n_miss, len(items)) > Fraction(20, 100): + ok = False; ans["unscorable"].append("%s:%s" % (cid, code)); continue + if n_miss == 0: out["subscales"][code] = sum(vals) + else: + pro = Decimal(sum(vals)) * Decimal(len(items)) / Decimal(len(vals)) + out["subscales"][code] = int(pro.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + if ok: + total = sum(out["subscales"].values()) + out["total"] = total + for name, (lo, hi) in bands: + if lo <= total <= hi: out["band"] = name + if out["band"] in ("moderate", "severe"): ans["moderate_or_severe"].append(cid) + if risk is not None: + cell = r["item_%02d" % risk].strip() + if cell not in missing_codes and int(cell) >= 2: ans["risk_flagged"].append(cid) + ans["clients"][cid] = out + return ans + +# ---------------------------------------------------------------- reliable change +def reliable_change(): + inst = dict((r["code"], r) for r in rows("instruments.csv")) + ans = {"instruments": {}, "results": {}, "recovered": [], "deteriorated": [], "no_post": []} + counts = {} + for r in rows("outcomes.csv"): + code, cid = r["instrument"], r["client_id"] + i = inst[code] + se = float(i["sd"]) * math.sqrt(1 - float(i["reliability"])) + sdiff = math.sqrt(2 * se * se) + ans["instruments"].setdefault(code, {})["s_diff"] = round(sdiff, 2) + if r["post_score"].strip() == "": + ans["no_post"].append("%s:%s" % (cid, code)); continue + pre, post, cut = float(r["pre_score"]), float(r["post_score"]), float(i["clinical_cutoff"]) + x = (post - pre) / sdiff + up_is_bad = i.get("direction", "higher_is_worse") == "higher_is_worse" + if up_is_bad: pre_clin, post_clin, better = pre >= cut, post >= cut, post < pre + else: pre_clin, post_clin, better = pre <= cut, post <= cut, post > pre + if not (x > 1.96 or x < -1.96): status = "unchanged" + elif not better: status = "deteriorated" + elif pre_clin and not post_clin: status = "recovered" + else: status = "improved" + ans["results"].setdefault(cid, {})[code] = {"rci": round(x, 2), "status": status} + if status in ("recovered", "deteriorated"): ans[status].append("%s:%s" % (cid, code)) + c = counts.setdefault(code, [0, 0]); c[0] += 1; c[1] += status == "recovered" + for code, (n, rec) in counts.items(): + ans["instruments"][code]["recovered_pct"] = round(100.0 * rec / n, 1) + return ans + +# ---------------------------------------------------------------- norms +def norms(): + table = {} + for r in rows("norms.csv"): + lo, hi = r["age_band"].split("-") + table.setdefault((r["scale"], r["sex"]), []).append((int(lo), int(hi), float(r["mean"]), float(r["sd"]))) + only_scale = sorted(set(k[0] for k in table))[0] + guide = text("norms_guide.md") + with_ranges = "## Ranges" in guide + ans = {"clients": {}, "no_norm_group": [], "high_or_above": []} + for r in rows("clients.csv"): + cid = r["client_id"] + if "age" in r: age = int(r["age"]) + else: + by, bm, bd = [int(x) for x in r["date_of_birth"].split("-")] + ty, tm, td = [int(x) for x in r["test_date"].split("-")] + age = ty - by + if tm < bm or (tm == bm and td < bd): age -= 1 + scale = r.get("scale") or only_scale + group = [g for g in table[(scale, r["sex"])] if g[0] <= age <= g[1]] + if not group: + if cid not in ans["no_norm_group"]: ans["no_norm_group"].append(cid) + continue + z = (float(r["raw_score"]) - group[0][2]) / group[0][3] + t = 50 + 10 * z + res = {"z": round(z, 2), "t_score": round(t, 1), "percentile": round(50 * (1 + math.erf(z / math.sqrt(2))), 1)} + if with_ranges: + res["range"] = "very-high" if t >= 70 else "high" if t >= 60 else "average" if t >= 40 else "low" + if t >= 60: ans["high_or_above"].append("%s:%s" % (cid, scale)) + c = ans["clients"].setdefault(cid, {"age": age, "scales": {}}) + c["scales"][scale] = res + else: + res["age"] = age + ans["clients"][cid] = res + return ans + +# ---------------------------------------------------------------- reliability +def variance(xs): + m = sum(xs) / len(xs) + return sum((x - m) * (x - m) for x in xs) / (len(xs) - 1) + +def corr(xs, ys): + n = len(xs); mx = sum(xs) / n; my = sum(ys) / n + cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (n - 1) + return cov / math.sqrt(variance(xs) * variance(ys)) + +def alpha_of(cols): + k = len(cols) + totals = [sum(c[i] for c in cols) for i in range(len(cols[0]))] + return k / (k - 1) * (1 - sum(variance(c) for c in cols) / variance(totals)) + +def reliability(): + notes = text("reliability_notes.md") + m = re.search(r"^Reverse-keyed items:([^.]*)\.", notes, re.M) + reverse = set(re.findall(r"q\d+", m.group(1))) if m else set() + data = rows("item_responses.csv") + qs = sorted([c for c in data[0] if re.match(r"^q\d+$", c)], key=lambda c: int(c[1:])) + complete = [r for r in data if all(r[q].strip() != "" for q in qs)] + cols = dict((q, [(6 - int(r[q])) if q in reverse else int(r[q]) for r in complete]) for q in qs) + alpha = alpha_of([cols[q] for q in qs]) + totals = [sum(cols[q][i] for q in qs) for i in range(len(complete))] + ans = {"items": {}, "total_variance": round(variance(totals), 3), "alpha": round(alpha, 3), "weak_items": [], "n_used": len(complete)} + best, best_alpha = None, None + for q in qs: + rest = [t - x for t, x in zip(totals, cols[q])] + rr = corr(cols[q], rest) + a_del = alpha_of([cols[p] for p in qs if p != q]) + ans["items"][q] = {"mean": round(sum(cols[q]) / len(cols[q]), 2), "variance": round(variance(cols[q]), 3), + "item_rest_r": round(rr, 3), "alpha_if_deleted": round(a_del, 3)} + if rr < 0.30: ans["weak_items"].append(q) + if best is None or a_del > best_alpha: best, best_alpha = q, a_del + ans["best_item_to_drop"] = best + ans["alpha_gain"] = round(best_alpha - alpha, 3) + return ans + +if os.path.exists("scoring_manual.md"): answer = scoring() +elif os.path.exists("rci_rules.md"): answer = reliable_change() +elif os.path.exists("norms.csv"): answer = norms() +else: answer = reliability() +with open("answer.json", "w") as f: json.dump(answer, f, indent=1) diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0083/solution/solve.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e181145ecdd916c6ebba65c9c854625c6e95d9ab --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0083/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -e +cd /app +python3 /solution/oracle.py diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0083/task.toml b/tasks/psychometrics/psychometrics-scoring-d3-t0083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..441257a72df55afefe96896ef25c5689e8828f57 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0083/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "psychometrics" +tags = ["psychometrics", "scoring", "isced-0313", "train"] +isced_f = "0313" +family = "scoring" +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/psychometrics/psychometrics-scoring-d3-t0083/tests/checks.json b/tasks/psychometrics/psychometrics-scoring-d3-t0083/tests/checks.json new file mode 100644 index 0000000000000000000000000000000000000000..25f5522ed8abdc720bc542763a0ae846ff606951 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-d3-t0083/tests/checks.json @@ -0,0 +1,271 @@ +[ + { + "path": "clients.C246.subscales.LOW", + "type": "int", + "value": 12, + "weight": 1.0 + }, + { + "path": "clients.C246.subscales.CON", + "type": "int", + "value": 13, + "weight": 1.0 + }, + { + "path": "clients.C246.subscales.SLP", + "type": "int", + "value": 14, + "weight": 1.0 + }, + { + "path": "clients.C246.subscales.SOC", + "type": "int", + "value": 31, + "weight": 1.0 + }, + { + "path": "clients.C246.total", + "type": "int", + "value": 70, + "weight": 1.0 + }, + { + "path": "clients.C246.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C255.subscales.LOW", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C255.subscales.CON", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C255.subscales.SLP", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C255.subscales.SOC", + "type": "int", + "value": 21, + "weight": 1.0 + }, + { + "path": "clients.C255.total", + "type": "int", + "value": 44, + "weight": 1.0 + }, + { + "path": "clients.C255.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C268.subscales.CON", + "type": "int", + "value": 3, + "weight": 1.0 + }, + { + "path": "clients.C268.subscales.SLP", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C268.subscales.SOC", + "type": "int", + "value": 8, + "weight": 1.0 + }, + { + "path": "clients.C309.subscales.LOW", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C309.subscales.CON", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C309.subscales.SLP", + "type": "int", + "value": 10, + "weight": 1.0 + }, + { + "path": "clients.C309.subscales.SOC", + "type": "int", + "value": 23, + "weight": 1.0 + }, + { + "path": "clients.C309.total", + "type": "int", + "value": 52, + "weight": 1.0 + }, + { + "path": "clients.C309.band", + "type": "str", + "value": "moderate", + "weight": 1.0 + }, + { + "path": "clients.C311.subscales.LOW", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C311.subscales.CON", + "type": "int", + "value": 11, + "weight": 1.0 + }, + { + "path": "clients.C311.subscales.SLP", + "type": "int", + "value": 16, + "weight": 1.0 + }, + { + "path": "clients.C311.subscales.SOC", + "type": "int", + "value": 36, + "weight": 1.0 + }, + { + "path": "clients.C311.total", + "type": "int", + "value": 79, + "weight": 1.0 + }, + { + "path": "clients.C311.band", + "type": "str", + "value": "severe", + "weight": 1.0 + }, + { + "path": "clients.C344.subscales.LOW", + "type": "int", + "value": 2, + "weight": 1.0 + }, + { + "path": "clients.C344.subscales.CON", + "type": "int", + "value": 0, + "weight": 1.0 + }, + { + "path": "clients.C344.subscales.SLP", + "type": "int", + "value": 1, + "weight": 1.0 + }, + { + "path": "clients.C344.subscales.SOC", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C344.total", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C344.band", + "type": "str", + "value": "minimal", + "weight": 1.0 + }, + { + "path": "clients.C361.subscales.LOW", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C361.subscales.CON", + "type": "int", + "value": 6, + "weight": 1.0 + }, + { + "path": "clients.C361.subscales.SLP", + "type": "int", + "value": 5, + "weight": 1.0 + }, + { + "path": "clients.C361.subscales.SOC", + "type": "int", + "value": 9, + "weight": 1.0 + }, + { + "path": "clients.C361.total", + "type": "int", + "value": 25, + "weight": 1.0 + }, + { + "path": "clients.C361.band", + "type": "str", + "value": "mild", + "weight": 1.0 + }, + { + "path": "moderate_or_severe", + "type": "set", + "value": [ + "C246", + "C255", + "C309", + "C311" + ], + "item": "str", + "weight": 2 + }, + { + "path": "unscorable", + "type": "set", + "value": [ + "C268:LOW" + ], + "item": "str", + "weight": 2 + }, + { + "path": "risk_flagged", + "type": "set", + "value": [ + "C246", + "C255", + "C268", + "C309", + "C311", + "C361" + ], + "item": "str", + "weight": 2 + } +] diff --git a/tasks/psychometrics/psychometrics-scoring-d3-t0083/tests/test.sh b/tasks/psychometrics/psychometrics-scoring-d3-t0083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3f1149df2619f3f11ecc1e06c9ee5b6599e8ab71 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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/psychometrics/psychometrics-scoring-d3-t0083/tests/verify.py b/tasks/psychometrics/psychometrics-scoring-d3-t0083/tests/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..e03124340b6015e692f6944976f4dedcadc0e722 --- /dev/null +++ b/tasks/psychometrics/psychometrics-scoring-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()