ClarusC64's picture
Create scorer.py
a4dcb8d verified
# scorer.py
# Autonomous Vehicles Context and Regime Recognition — v01 scorer
#
# Dataset file:
# - data/context_regime_recognition_av.csv
#
# Expected CSV columns used for scoring:
# - expected_response (VALID_CONTEXT|CONTEXT_BREAKDOWN|CLARIFY)
# - expected_rationale_bullets (pipe-separated)
# - expected_context (free text, optional)
# - regime_boundary (free text, optional)
# - boundary_reason (free text, optional)
# - disallowed_assumptions (free text, optional, may be pipe-separated)
#
# Expected model output format (loose):
# Response: VALID_CONTEXT|CONTEXT_BREAKDOWN|CLARIFY
# Rationale:
# - ...
# Context:
# - ...
#
# Scoring 0–100
# - Response match: 40
# - Rationale coverage: 35
# - Boundary identification: 15
# - Assumption control: 10
#
# Heuristic scorer, no external dependencies.
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Dict, List, Tuple
RESPONSES = ("VALID_CONTEXT", "CONTEXT_BREAKDOWN", "CLARIFY")
@dataclass
class ScoreResult:
score_0_100: int
subscores: Dict[str, float]
details: Dict[str, object]
def normalize_text(s: str) -> str:
s = s or ""
s = s.strip().lower()
s = re.sub(r"\s+", " ", s)
return s
def split_pipe_list(s: str) -> List[str]:
if not s:
return []
return [p.strip() for p in s.split("|") if p.strip()]
def token_set(s: str) -> set:
s = normalize_text(s)
return set(re.findall(r"[a-z0-9]+", s))
def jaccard(a: str, b: str) -> float:
sa = token_set(a)
sb = token_set(b)
if not sa or not sb:
return 0.0
return len(sa & sb) / len(sa | sb)
def bullets_from_text(s: str) -> List[str]:
s = s or ""
lines = [ln.strip() for ln in s.splitlines() if ln.strip()]
bullets: List[str] = []
for ln in lines:
ln2 = re.sub(r"^\s*[\-\u2022\*]\s*", "", ln)
ln2 = re.sub(r"^\s*\d+[\)\.]\s*", "", ln2)
if ln2 != ln:
bullets.append(ln2.strip())
if bullets:
return bullets
chunks = re.split(r"[.;]\s+", s)
return [c.strip() for c in chunks if c.strip()][:12]
def best_match_score(needle: str, haystack_items: List[str]) -> float:
if not needle or not haystack_items:
return 0.0
sims = [jaccard(needle, h) for h in haystack_items]
return max(sims) if sims else 0.0
def count_covered(expected_items: List[str], model_items: List[str], threshold: float = 0.22) -> Tuple[int, List[Tuple[str, float]]]:
covered = 0
per: List[Tuple[str, float]] = []
for exp in expected_items:
sim = best_match_score(exp, model_items)
per.append((exp, sim))
if sim >= threshold:
covered += 1
return covered, per
def extract_response(model_output: str) -> str:
txt = normalize_text(model_output)
m = re.search(
r"\b(response|decision|action)\b\s*[:\-]?\s*(valid_context|valid context|context_breakdown|context breakdown|clarify)\b",
txt,
)
if m:
r = m.group(2).upper().replace(" ", "_")
if r in RESPONSES:
return r
if re.search(r"\bcontext_breakdown\b", txt) or re.search(r"\bcontext breakdown\b", txt):
return "CONTEXT_BREAKDOWN"
if re.search(r"\bvalid_context\b", txt) or re.search(r"\bvalid context\b", txt):
return "VALID_CONTEXT"
if re.search(r"\bclarify\b", txt):
return "CLARIFY"
return "UNKNOWN"
def response_points(pred: str, exp: str) -> float:
pred = (pred or "").upper()
exp = (exp or "").upper()
if pred == exp and pred in RESPONSES:
return 40.0
if pred in RESPONSES and exp in RESPONSES:
if (pred, exp) in {("CLARIFY", "CONTEXT_BREAKDOWN"), ("CONTEXT_BREAKDOWN", "CLARIFY")}:
return 22.0
return 10.0
return 0.0
def rationale_points(model_output: str, expected_bullets: List[str], boundary_reason: str) -> Tuple[float, List[Tuple[str, float]]]:
"""
0–35 points.
Cover expected bullets; allow boundary_reason as extra.
"""
if not expected_bullets and not (boundary_reason or "").strip():
return 20.0, []
model_items = bullets_from_text(model_output)
exp_items = list(expected_bullets)
if (boundary_reason or "").strip():
exp_items.append(boundary_reason.strip())
covered, per = count_covered(exp_items, model_items, threshold=0.22)
ratio = covered / max(1, len(exp_items))
return 35.0 * ratio, per
def boundary_id_points(model_output: str, expected_context: str, regime_boundary: str) -> float:
"""
0–15 points.
Reward naming context and boundary (school zone, construction, rain, emergency vehicle).
"""
if not model_output:
return 0.0
out = normalize_text(model_output)
has_context_lang = bool(
re.search(r"\b(context|zone|construction|school|rain|night|emergency|merge|roundabout)\b", out)
)
base = 6.0 if has_context_lang else 3.0
ctx = (expected_context or "").strip()
bnd = (regime_boundary or "").strip()
sim_ctx = jaccard(model_output, ctx) if ctx else 0.0
sim_bnd = jaccard(model_output, bnd) if bnd else 0.0
pts = base
if ctx and sim_ctx >= 0.10:
pts += 5.0
elif ctx and sim_ctx >= 0.06:
pts += 3.0
if bnd and sim_bnd >= 0.10:
pts += 5.0
elif bnd and sim_bnd >= 0.06:
pts += 3.0
return min(15.0, pts)
def assumption_control_points(model_output: str, disallowed_assumptions: str) -> Tuple[float, List[str]]:
"""
0–10 points.
Penalize if model repeats disallowed assumptions or uses generic assumption language.
"""
if not model_output:
return 0.0, []
hits: List[str] = []
items = bullets_from_text(model_output)
dis = (disallowed_assumptions or "").strip()
dis_list = split_pipe_list(dis) if "|" in dis else ([dis] if dis else [])
for d in dis_list:
sim = best_match_score(d, items)
if sim >= 0.18:
hits.append(d)
t = normalize_text(model_output)
if re.search(r"\b(probably|likely|should be fine|as usual|standard)\b", t):
hits.append("Generic assumption language")
pts = 10.0 - 4.0 * len(hits)
return max(0.0, pts), hits
def score_one(row: Dict[str, str], model_output: str) -> ScoreResult:
exp_resp = (row.get("expected_response") or "").strip().upper()
exp_bullets = split_pipe_list(row.get("expected_rationale_bullets") or "")
expected_context = row.get("expected_context") or ""
regime_boundary = row.get("regime_boundary") or ""
boundary_reason = row.get("boundary_reason") or ""
disallowed = row.get("disallowed_assumptions") or ""
pred_resp = extract_response(model_output)
r_points = response_points(pred_resp, exp_resp)
ra_points, ra_sims = rationale_points(model_output, exp_bullets, boundary_reason)
b_points = boundary_id_points(model_output, expected_context, regime_boundary)
a_points, a_hits = assumption_control_points(model_output, disallowed)
total = r_points + ra_points + b_points + a_points
total_int = int(round(max(0.0, min(100.0, total))))
subs = {
"response_match_40": round(r_points, 2),
"rationale_coverage_35": round(ra_points, 2),
"boundary_identification_15": round(b_points, 2),
"assumption_control_10": round(a_points, 2),
}
details = {
"expected_response": exp_resp,
"predicted_response": pred_resp,
"rationale_match_sims": [(e, round(s, 3)) for e, s in ra_sims],
"assumption_hits": a_hits,
}
return ScoreResult(score_0_100=total_int, subscores=subs, details=details)
def score(row: Dict[str, str], model_output: str) -> Dict[str, object]:
res = score_one(row, model_output)
return {
"score_0_100": res.score_0_100,
"subscores": res.subscores,
"details": res.details,
}
if __name__ == "__main__":
demo_row = {
"expected_response": "CONTEXT_BREAKDOWN",
"expected_rationale_bullets": "Rain reduces friction and sensor confidence|Dry assumptions invalid",
"expected_context": "Adverse weather",
"regime_boundary": "Weather regime shift",
"boundary_reason": "Reduced friction and perception reliability",
"disallowed_assumptions": "Assuming weather irrelevant",
}
demo_out = """Response: CONTEXT_BREAKDOWN
Rationale:
- Heavy rain reduces friction and degrades sensor confidence, so dry-road assumptions no longer hold.
- The driving model should switch to an adverse-weather regime with larger safety margins.
"""
print(score(demo_row, demo_out))