File size: 9,683 Bytes
af5b4af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""Independent solvers: read only the input files and the instruction, as an agent would, and must
score 1 on every level of every new science family. They show the instruction is enough to get the
answer and that the stated tolerances are reachable with ordinary methods."""

import csv
import io
import json
import math
import os
import re
import statistics
import tempfile

import numpy as np
import pytest
from scipy.signal import lombscargle

os.environ.setdefault("TERMINAL_DESK_APP", tempfile.mkdtemp(prefix="td-solve-"))

from terminal_desk.families import FAMILIES  # noqa: E402
from terminal_desk.models import Tbench2Action  # noqa: E402
from terminal_desk.server.environment import TerminalDeskEnvironment  # noqa: E402


def rows(text):
    return list(csv.DictReader(io.StringIO(text)))


def solve_units(files, instruction):
    conv = {}
    canon = {}
    for r in rows(files["conversions.txt"]):
        canon[r["test"]] = r["canonical_unit"]
        conv[(r["test"], norm_unit(r["other_unit"]))] = float(r["multiply_by"])
    latest = {}
    for r in rows(files["labs.csv"]):
        unit = norm_unit(r["unit"])
        value = float(r["value"])
        if unit != norm_unit(canon[r["test"]]):
            value *= conv[(r["test"], unit)]
        latest[(r["sample_id"], r["test"])] = value
    if "qc_notes.txt" in files:
        m = re.search(r"the (\w+) result for (\w+) was", files["qc_notes.txt"])
        latest.pop((m.group(2), m.group(1)), None)
    out = "sample_id,test,value\n" + "".join(f"{s},{t},{v:.4f}\n" for (s, t), v in latest.items())
    return "harmonized.csv", out


def norm_unit(u):
    return u.strip().lower().replace("µ", "u").replace("micro", "u").replace(" per ", "/")


def solve_protein(files, instruction):
    table = rows(files["expression.csv"])
    if "samples.csv" in files:
        cond = {r["run"]: r["condition"] for r in rows(files["samples.csv"])}
    else:
        cond = {c: ("control" if c.startswith("ctrl") else "treated") for c in table[0] if c != "protein"}
    top_n = int(re.search(r"the (\d+) proteins", instruction).group(1))
    out = []
    for r in table:
        c = [float(r[k]) for k, v in cond.items() if v == "control" and r[k] != ""]
        t = [float(r[k]) for k, v in cond.items() if v == "treated" and r[k] != ""]
        if len(c) < 2 or len(t) < 2:
            continue
        if "Welch" in instruction:
            lc, lt = np.log2(c), np.log2(t)
            tstat = (lt.mean() - lc.mean()) / math.sqrt(lc.var(ddof=1) / len(lc) + lt.var(ddof=1) / len(lt))
            if abs(tstat) < 4:
                continue
        out.append((r["protein"], math.log2(statistics.mean(t) / statistics.mean(c))))
    out.sort(key=lambda kv: -abs(kv[1]))
    return "top_hits.csv", "protein,log2_fc\n" + "".join(f"{p},{v:.4f}\n" for p, v in out[:top_n])


def solve_flood(files, instruction):
    w0, w1 = re.findall(r"\d{4}-\d\d-\d\d", instruction)[:2]
    thr = {}
    for r in rows(files["stations.csv"]):
        if "unit" in r:
            thr[r["station_id"]] = float(r["flood_stage"]) * (3.28084 if r["unit"] == "m" else 1)
        else:
            thr[r["station_id"]] = float(r["flood_stage_ft"])
    count = {}
    for r in rows(files["gauge.csv"]):
        if r["stage_ft"] == "" or not (w0 <= r["date"] <= w1):
            continue
        if float(r["stage_ft"]) >= thr[r["station_id"]]:
            count[r["station_id"]] = count.get(r["station_id"], 0) + 1
    return "flood_results.csv", "station_id,flood_days\n" + "".join(f"{s},{n}\n" for s, n in count.items())


def solve_trend(files, instruction):
    data = rows(files["water_temperature.csv"])
    if "month" in data[0]:
        by_year = {}
        for r in data:
            by_year.setdefault(int(r["year"]), []).append(float(r["surface_temp_c"]))
        pts = sorted((y, sum(v) / 12) for y, v in by_year.items() if len(v) == 12)
    else:
        pts = [(int(r["year"]), float(r["surface_temp_c"])) for r in data]
    x = np.array([p[0] for p in pts], float)
    y = np.array([p[1] for p in pts])
    ols = np.polyfit(x, y, 1)[0] * 10
    sen = float(np.median([(y[j] - y[i]) / (x[j] - x[i]) for i in range(len(x)) for j in range(i + 1, len(x))])) * 10
    out = {"ols_slope_c_per_decade": ols, "sen_slope_c_per_decade": sen}
    if "mk_z" in instruction:
        n = len(y)
        s = sum(np.sign(y[j] - y[i]) for i in range(n) for j in range(i + 1, n))
        sd = math.sqrt(n * (n - 1) * (2 * n + 5) / 18)
        z = (s - 1) / sd if s > 0 else (s + 1) / sd if s < 0 else 0.0
        out.update({"mk_z": z, "significant": "yes" if abs(z) > 1.96 else "no"})
    return "trend.json", json.dumps(out)


def solve_quake(files, instruction):
    b = rows(files["boundary.csv"])
    verts = [(float(r["lat"]), float(r["lon"])) for r in b]
    best = None
    for r in rows(files["quakes.csv"]):
        if "magnitude 5.0" in instruction and float(r["mag"]) < 5.0:
            continue
        if "70 km" in instruction and float(r["depth_km"]) > 70:
            continue
        lat, lon = float(r["latitude"]), float(r["longitude"])
        d = min(hav(lat, lon, a, o) for a, o in verts)
        if best is None or d > best[1]:
            best = (r["id"], d)
    return "answer.json", json.dumps({"id": best[0], "distance_km": best[1]})


def hav(la1, lo1, la2, lo2):
    p1, p2 = math.radians(la1), math.radians(la2)
    a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lo2 - lo1) / 2) ** 2
    return 2 * 6371 * math.asin(math.sqrt(a))


def solve_period(files, instruction):
    data = rows(files["tess_lc.csv"])
    col = "flux_e_per_s" if "flux_e_per_s" in data[0] else "normalized_flux"
    t = np.array([float(r["time_mjd"]) for r in data])
    f = np.array([float(r[col]) for r in data])
    good = np.array([r["quality"] == "0" for r in data]) if "quality 0" in instruction else np.ones(len(t), bool)
    if "two sectors" in instruction:
        gap = int(np.argmax(np.diff(t))) + 1
        for sl in (slice(0, gap), slice(gap, None)):
            seg = f[sl].copy()
            f[sl] = seg / np.median(seg[good[sl]])
    t, f = t[good], f[good]
    freqs = np.linspace(1 / 15, 1 / 0.5, 5000)
    power = lombscargle(t, f - f.mean(), 2 * np.pi * freqs)
    return "period.json", json.dumps({"period_days": 1 / freqs[np.argmax(power)]})


def pick(x):
    e = x ** 2
    c = np.concatenate([[0.0], np.cumsum(e)])
    sta, lta = 50, 500
    r = np.zeros(len(x))
    for i in range(sta + lta, len(x)):
        r[i] = ((c[i] - c[i - sta]) / sta) / max((c[i - sta] - c[i - sta - lta]) / lta, 1e-12)
    p = int(np.argmax(r > 4))
    sta_e = np.array([(c[i] - c[i - sta]) / sta if i >= sta else 0 for i in range(len(x))])
    p_e = sta_e[p:p + 200].max()
    cand = [i for i in range(p + 200, len(x)) if r[i] > 3 and sta_e[i] > 2 * p_e]
    return p, cand[0]


def solve_picking(files, instruction):
    if "trace.csv" in files:
        x = np.array([float(r["amplitude"]) for r in rows(files["trace.csv"])])
        p, s = pick(x)
        out = {"p_index": p} if "s_index" not in instruction else {"p_index": p, "s_index": s}
        return "picks.json", json.dumps(out)
    lines = ["station,p_index,s_index"]
    for name, text in files.items():
        x = np.array([float(r["amplitude"]) for r in rows(text)])
        p, s = pick(x)
        lines.append(f"{name.split('/')[-1][:-4]},{p},{s}")
    return "picks.csv", "\n".join(lines) + "\n"


def vitals(t, x):
    fs = 1 / (t[1] - t[0])
    x = x - np.polyval(np.polyfit(t, x, 1), t)
    n = 1 << 16
    spec = np.abs(np.fft.rfft(x, n))
    f = np.fft.rfftfreq(n, 1 / fs)
    out = []
    for lo, hi in ((0.1, 0.6), (0.8, 2.0)):
        band = (f >= lo) & (f <= hi)
        out.append(float(f[band][np.argmax(spec[band])] * 60))
    return out


def solve_vitals(files, instruction):
    if "chest.csv" in files:
        d = rows(files["chest.csv"])
        t = np.array([float(r["t_s"]) for r in d])
        x = np.array([float(r["displacement_mm"]) for r in d])
        br, hr = vitals(t, x)
        out = {"breaths_per_min": br}
        if "heart_bpm" in instruction:
            out["heart_bpm"] = hr
        return "vitals.json", json.dumps(out)
    lines = ["recording,breaths_per_min,heart_bpm"]
    for name, text in sorted(files.items()):
        first, rest = text.split("\n", 1)
        fs = float(first.split("=")[1])
        x = np.array([float(v) for v in rest.split("\n")[1:] if v])
        br, hr = vitals(np.arange(len(x)) / fs, x)
        lines.append(f"{name.split('/')[-1][:-4]},{br:.2f},{hr:.2f}")
    return "vitals.csv", "\n".join(lines) + "\n"


SOLVERS = {
    "sci_units": solve_units,
    "sci_protein": solve_protein,
    "sci_flood": solve_flood,
    "sci_trend": solve_trend,
    "sci_quake": solve_quake,
    "sci_period": solve_period,
    "sci_picking": solve_picking,
    "sci_vitals": solve_vitals,
}
CASES = [(fid, lv, inst) for fid in SOLVERS for lv in FAMILIES[fid].levels for inst in range(4)]


@pytest.mark.parametrize("family,level,instance", CASES)
def test_independent_solver_scores_one(family, level, instance):
    env = TerminalDeskEnvironment()
    task_id = f"{family}-L{level}-i{instance}"
    obs = env.reset(task_id=task_id)
    built = env._ep["built"]
    files = {k: (v if isinstance(v, str) else v.decode()) for k, v in built.files.items()}
    path, content = SOLVERS[family](files, obs.instruction)
    assert path == built.artifact.path
    assert env.step(Tbench2Action(action_type="write_file", file_path=path, content=content)).success
    result = env.step(Tbench2Action(action_type="evaluate"))
    assert result.reward == 1.0, (task_id, result.output, content[:400])