File size: 8,566 Bytes
32030e4 | 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 | """Scorers. Every scorer returns a float in [0, 1]; malformed responses score 0.
Calibration (stated confidence vs achieved score) is reported separately by
``calibration_term`` and aggregated at report level, not mixed into task scores.
"""
from __future__ import annotations
import math
from itertools import combinations
EPS = 1e-12
def _num(x):
try:
v = float(x)
except (TypeError, ValueError):
return None
return v if math.isfinite(v) else None
def interval_score01(interval, truth: float, scale: float, *, alpha: float = 0.1, log: bool = False) -> float:
"""Proper interval score mapped to [0, 1].
IS = width + (2/alpha) * distance outside; score = exp(-IS / (4 * scale)).
A correct interval of width 2*scale scores ~0.61; an exact point scores 1;
missing by one scale costs ~20 scales (score ~0.007).
"""
if not isinstance(interval, (list, tuple)) or len(interval) != 2:
return 0.0
lo, hi = _num(interval[0]), _num(interval[1])
if lo is None or hi is None or truth is None:
return 0.0
if lo > hi:
lo, hi = hi, lo
if log:
if lo <= 0 or hi <= 0 or truth <= 0:
return 0.0
lo, hi, truth = math.log10(lo), math.log10(hi), math.log10(truth)
width = hi - lo
miss = max(0.0, lo - truth) + max(0.0, truth - hi)
return math.exp(-(width + (2.0 / alpha) * miss) / (4.0 * scale))
def dT_scale(truth: float, tol_abs: float = 0.5, rel: float = 0.10) -> float:
return max(tol_abs, rel * abs(truth))
def score_ranking(pred_order, truth_values: dict, tie_eps: float, relative: bool = False) -> float:
"""Fraction of correctly ordered pairs among pairs separated by more than tie_eps."""
labels = list(truth_values)
if not isinstance(pred_order, (list, tuple)) or sorted(map(str, pred_order)) != sorted(labels):
return 0.0
pos = {lab: i for i, lab in enumerate(map(str, pred_order))}
total = correct = 0
for a, b in combinations(labels, 2):
va, vb = truth_values[a], truth_values[b]
gap = abs(va - vb) / (max(abs(va), abs(vb), EPS) if relative else 1.0)
if gap <= tie_eps:
continue
total += 1
correct += (pos[a] < pos[b]) == (va < vb)
return correct / total if total else 1.0
def direction(delta: float, tol: float) -> str:
return "about_the_same" if abs(delta) <= tol else ("higher" if delta > 0 else "lower")
def score_limit_check(pred: dict, ans: dict) -> float:
if not isinstance(pred, dict):
return 0.0
keys = list(ans["per_limit"])
per = sum(str(pred.get("per_limit", {}).get(k, "")).lower() == ans["per_limit"][k] for k in keys) / len(keys)
overall = str(pred.get("overall", "")).lower() == ans["overall"]
binding = str(pred.get("binding_limit", "")).lower() == ans["binding_limit"]
return 0.5 * per + 0.25 * overall + 0.25 * binding
def score_approval(pred, true_set) -> float:
"""Constraint-gated: approving any non-compliant design scores 0."""
if not isinstance(pred, (list, tuple)):
return 0.0
pred_set, true_set = set(map(str, pred)), set(true_set)
if pred_set - true_set:
return 0.0
if not true_set:
return 1.0 if not pred_set else 0.0
return len(pred_set & true_set) / len(true_set)
def score_review(pred: dict, ans: dict) -> float:
"""Approving a faulty result scores 0; a correct rejection earns 0.7 + 0.3 for the right reason."""
if not isinstance(pred, dict):
return 0.0
decision = str(pred.get("decision", "")).lower()
if decision not in {"approve", "reject"}:
return 0.0
if ans["decision"] == "approve":
return 1.0 if decision == "approve" else 0.0
if decision == "approve":
return 0.0
return 0.7 + 0.3 * (str(pred.get("reason", "")).lower() == ans["reason"])
def score_campaign(pred: dict, ans: dict) -> dict[str, float]:
"""Fraction right at each step of a campaign_reconstruction task."""
def letter(value) -> str:
return str(value).strip().upper()
def outcome(value) -> str:
return str(value).strip().lower()
links = pred.get("links") if isinstance(pred.get("links"), dict) else {}
signoff = pred.get("signoff") if isinstance(pred.get("signoff"), dict) else {}
return {"links": sum(letter(links.get(k)) == v for k, v in ans["links"].items()) / len(ans["links"]),
"misfiled": float(letter(pred.get("misfiled")) == ans["misfiled"]),
"signoff": sum(outcome(signoff.get(k)) == v for k, v in ans["signoff"].items()) / len(ans["signoff"])}
def _verdicts(pred, truth: dict) -> float:
"""Fraction of labelled verdicts right; anything but an object scores 0."""
pred = pred if isinstance(pred, dict) else {}
return sum(str(pred.get(k)).strip().lower() == v for k, v in truth.items()) / len(truth)
def score_evidence(pred: dict, ans: dict) -> dict[str, float]:
return {"temperature": _verdicts(pred.get("temperature"), ans["temperature"]),
"pressure": _verdicts(pred.get("pressure"), ans["pressure"])}
def score_envelope(pred: dict, ans: dict) -> dict[str, float]:
ranking = pred.get("ranking")
shown = [str(item).strip().upper() for item in ranking] if isinstance(ranking, (list, tuple)) else None
return {"ranking": float(shown == ans["ranking"]), "regimes": _verdicts(pred.get("regimes"), ans["regimes"])}
def calibration_term(confidence, achieved: float) -> float | None:
c = _num(confidence)
if c is None or not 0.0 <= c <= 1.0:
return None
return (c - achieved) ** 2
def score_task(task: dict, response: dict) -> dict:
"""Score a model response (the final ``submit`` payload) against a task."""
fam, ans, p = task["family"], task.get("answer"), task["scoring"]["params"]
if ans is None:
raise ValueError(f"{task['task_id']} has no answer ({task.get('answer_status')})")
if not isinstance(response, dict):
return {"score": 0.0, "calibration_sq_error": None, "parts": {"format": 0}}
parts: dict[str, float] = {}
if fam == "case_ranking":
parts["ranking"] = score_ranking(response.get("ranking"), ans["values"], p["tie_eps"], p.get("relative", False))
score = parts["ranking"]
elif fam == "estimation":
parts["dT_max_K"] = interval_score01(response.get("dT_max_K"), ans["dT_max_K"], p["scale_dT_max_K"])
parts["coolant_rise_K"] = interval_score01(response.get("coolant_rise_K"), ans["coolant_rise_K"], p["scale_coolant_rise_K"])
parts["dP_kPa"] = interval_score01(response.get("dP_kPa"), ans["dP_kPa"], p["log_scale_dP"], log=True)
score = sum(parts.values()) / 3
elif fam in {"operating_point_transfer", "evidence_budget_transfer"}:
parts["dT_max_K"] = interval_score01(response.get("dT_max_K"), ans["dT_max_K"], p["scale_dT_max_K"])
parts["dP_kPa"] = interval_score01(response.get("dP_kPa"), ans["dP_kPa"], p["log_scale_dP"], log=True)
if "direction" in ans:
d = response.get("direction") or {}
parts["direction"] = sum(str(d.get(k, "")).lower() == v for k, v in ans["direction"].items()) / len(ans["direction"])
score = 0.4 * parts["dT_max_K"] + 0.3 * parts["dP_kPa"] + 0.3 * parts["direction"]
else:
score = 0.6 * parts["dT_max_K"] + 0.4 * parts["dP_kPa"]
elif fam == "limit_check":
score = parts["limit_check"] = score_limit_check(response, ans)
elif fam == "approval_choice":
score = parts["approval"] = score_approval(response.get("approve"), ans["approve"])
elif fam == "result_review":
score = parts["review"] = score_review(response, ans)
elif fam in ("campaign_reconstruction", "tool_campaign"):
parts = score_campaign(response, ans)
score = float(all(value == 1 for value in parts.values()))
elif fam in ("evidence_signoff", "tool_signoff", "duty_signoff"):
parts = score_evidence(response, ans)
score = float(all(value == 1 for value in parts.values()))
elif fam in ("operating_envelope", "tool_envelope"):
parts = score_envelope(response, ans)
score = float(all(value == 1 for value in parts.values()))
elif fam == "regime_recognition":
score = parts["regime"] = float(str(response.get("regime", "")).strip().lower() == ans["regime"])
else:
raise ValueError(f"unknown family {fam}")
return {"score": float(score), "calibration_sq_error": calibration_term(response.get("confidence"), score),
"parts": parts}
|