"""Natural science: analyse an experiment's data with a Python tool and report the requested quantities.""" import math from typing import Any, Literal from pydantic import Field from ..core import Action, ProxyTask, Step, clip, run_python class LabAction(Action): kind: Literal["python", "answer"] = Field( description="python: run `code` (Python 3 standard library only; data.csv is in the working " "directory; print what you need). answer: submit `values`, which ends the episode.") code: str = Field(default="", description="Python source to run.") values: dict[str, Any] = Field(default_factory=dict, description="Final answer object.") def linfit(xs, ys): n = len(xs) mx, my = sum(xs) / n, sum(ys) / n slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs) return slope, my - slope * mx class LabAnalysis(ProxyTask): family = "science-lab" domain = "natural-science" Action = LabAction max_steps = 8 finish_action = {"kind": "answer", "values": {}} def setup(self): r = self.rng variant = self.seed % 4 if variant == 0: # Arrhenius ea, a = r.uniform(45, 90) * 1000, 10 ** r.uniform(8, 12) temps = [round(t, 1) for t in sorted(r.sample(range(290, 360, 5), 6))] rows = [(t, a * math.exp(-ea / (8.314 * t)) * math.exp(r.gauss(0, 0.03))) for t in temps] rows = [(t, float(f"{k:.4g}")) for t, k in rows] slope, icpt = linfit([1 / t for t, _ in rows], [math.log(k) for _, k in rows]) self.csv = "temperature_K,rate_constant_per_s\n" + "\n".join(f"{t},{k}" for t, k in rows) self.question = ("Estimate the activation energy from an Arrhenius plot: least-squares fit of ln(k) " "against 1/T over all rows (R = 8.314 J/(mol K)). Also predict k at 375 K from the fit.") self.answer = {"activation_energy_kj_per_mol": -slope * 8.314 / 1000, "k_at_375K_per_s": math.exp(icpt + slope / 375)} elif variant == 1: # bacterial growth doubling time mu = r.uniform(0.6, 1.4) od0 = r.uniform(0.01, 0.03) times = [i * 0.5 for i in range(14)] lag = r.choice([1.0, 1.5]) rows = [] for t in times: od = od0 if t < lag else od0 * math.exp(mu * (t - lag)) od = min(od, 1.6 - r.uniform(0, 0.1)) * math.exp(r.gauss(0, 0.02)) rows.append((t, round(od, 4))) window = [(t, od) for t, od in rows if 0.05 <= od <= 0.5] slope, _ = linfit([t for t, _ in window], [math.log(od) for _, od in window]) self.csv = "time_h,od600\n" + "\n".join(f"{t},{od}" for t, od in rows) self.question = ("Estimate the doubling time in the exponential phase: use only rows with " "0.05 <= OD600 <= 0.5, fit ln(OD600) against time by least squares, and report " "doubling time = ln(2)/slope in minutes, plus how many rows you used.") self.answer = {"doubling_time_min": math.log(2) / slope * 60, "rows_used": len(window)} elif variant == 2: # Hardy-Weinberg chi-square p = r.uniform(0.3, 0.7) n = r.randint(300, 900) skew = r.choice([0.0, 0.08]) aa = round(n * (p * p + skew)) ab = round(n * (2 * p * (1 - p) - 2 * skew)) bb = n - aa - ab pf = (2 * aa + ab) / (2 * n) exp_ = [n * pf * pf, 2 * n * pf * (1 - pf), n * (1 - pf) ** 2] chi = sum((o - e) ** 2 / e for o, e in zip([aa, ab, bb], exp_)) self.csv = "genotype,count\nAA," + f"{aa}\nAa,{ab}\naa,{bb}" self.question = ("Test these genotype counts for Hardy-Weinberg equilibrium: estimate the A allele " "frequency from the counts, compute the chi-square statistic over the three " "genotypes, and decide at alpha = 0.05 with 1 degree of freedom (critical value " '3.841). Report the frequency, the statistic and "reject" or "fail to reject".') self.answer = {"allele_frequency_A": pf, "chi_square": chi, "decision": "reject" if chi > 3.841 else "fail to reject"} else: # Beer-Lambert standard curve with an outlier flag eps = r.uniform(0.8, 2.5) concs = [0, 2, 4, 6, 8, 10] rows = [(c, round(eps * c / 10 + r.gauss(0, 0.004), 3)) for c in concs] bad = r.choice([2, 3, 4]) rows[bad] = (rows[bad][0], round(rows[bad][1] * 1.35, 3)) unknown = round(r.uniform(0.2, 0.9) * eps, 3) good = [row for i, row in enumerate(rows) if i != bad] slope, icpt = linfit([c for c, _ in good], [a for _, a in good]) self.csv = "standard_mg_per_L,absorbance,flag\n" + "\n".join( f"{c},{a},{'pipetting error' if i == bad else ''}" for i, (c, a) in enumerate(rows)) self.question = (f"Build a linear standard curve (absorbance against concentration, least squares with " f"intercept) excluding flagged rows, then find the concentration of a sample with " f"absorbance {unknown}. Report slope and the sample concentration in mg/L.") self.answer = {"slope": slope, "sample_mg_per_L": (unknown - icpt) / slope} def reset(self): keys = ", ".join(f'"{k}"' for k in self.answer) return {"stdout": "", "message": f"{self.question}\nThe data (also in data.csv):\n{self.csv}\n" f"Answer with values containing {keys}. Numbers are checked to 1%.", "actions_left": self.max_steps} def act(self, a): left = self.max_steps - self.steps if a.kind == "python": if not a.code.strip(): return Step({"stdout": "", "message": "code is empty", "actions_left": left}) code, out = run_python({"data.csv": self.csv, "main.py": a.code}, ["python", "-I", "main.py"]) return Step({"stdout": clip(out, 2500), "message": f"exit code {code}", "actions_left": left}) got = {str(k).lower(): v for k, v in a.values.items()} ok = True for key, want in self.answer.items(): val = got.get(key.lower()) if isinstance(want, str): ok &= isinstance(val, str) and val.strip().lower() == want elif isinstance(want, int) and not isinstance(want, bool): ok &= isinstance(val, (int, float)) and not isinstance(val, bool) and val == want else: ok &= isinstance(val, (int, float)) and not isinstance(val, bool) and math.isclose(val, want, rel_tol=0.01) return Step({"stdout": "", "message": "Answer recorded.", "actions_left": 0}, True, 1.0 if ok else 0.0) def oracle(self): return [{"kind": "python", "code": "print(open('data.csv').read()[:80])"}, {"kind": "answer", "values": self.answer}]