from dataclasses import dataclass from typing import Dict, Any, List import re @dataclass class ScoreResult: score: float details: Dict[str, Any] def _extract_horizon(text: str) -> int: m = re.search(r"(horizon|cycles)\s*[:=]?\s*(\d+)", (text or "").lower()) if m: return int(m.group(2)) return -1 def _extract_risk(text: str) -> float: m = re.search(r"(risk|cd).*?([0]\.\d+|1\.0)", (text or "").lower()) if m: try: return float(m.group(2)) except: return -1.0 return -1.0 def _extract_action(text: str) -> str: t = (text or "").lower() for k in [ "none","retune_timing","pulse_shape_adjust","pre_pulse_boost", "stability_tune","source_recalibration","power_derate", "full_timing_reset","shutdown_prepare","halt_source" ]: if k in t: return k return "" def score(sample: Dict[str, Any], prediction: str) -> ScoreResult: p = prediction or "" horizon = _extract_horizon(p) risk = _extract_risk(p) action = _extract_action(p) true_h_raw = sample.get("event_horizon_cycles", "") true_r_raw = sample.get("cd_uniformity_risk_score", "") true_a_raw = (sample.get("intervention_action", "") or "").lower() # If no ground truth in test row → structure check only if true_h_raw in ("", None) and true_r_raw in ("", None) and true_a_raw == "": s = 0.0 s += 0.4 * int(horizon > 0) s += 0.3 * int(0.0 <= risk <= 1.0) s += 0.3 * int(action != "") return ScoreResult(score=s, details={"mode": "format_only", "horizon": horizon, "risk": risk, "action": action}) try: true_h = int(true_h_raw) except: true_h = -1 try: true_r = float(true_r_raw) except: true_r = -1.0 h_score = 1.0 if horizon > 0 and true_h > 0 else 0.0 r_score = 1.0 - abs(risk - true_r) if true_r >= 0 and 0 <= risk <= 1 else 0.0 a_score = 1.0 if action == true_a_raw else 0.0 final = 0.4 * h_score + 0.4 * max(0.0, r_score) + 0.2 * a_score return ScoreResult(score=max(0.0, min(1.0, final)), details={"h": horizon, "r": risk, "a": action}) def aggregate(results: List[ScoreResult]) -> Dict[str, Any]: if not results: return {"mean": 0.0, "n": 0} return {"mean": sum(r.score for r in results)/len(results), "n": len(results)}