File size: 1,795 Bytes
f0c1a17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from dataclasses import dataclass
from typing import Dict, Any, List

VALID_AXES = {"thermal","cooling","mount","metrology","contamination","none"}

@dataclass
class ScoreResult:
    score: float
    details: Dict[str, Any]

def parse(prediction: str):
    # expected: drift_score,drift_flag,dominant_axis
    try:
        parts = [p.strip() for p in prediction.split(",")]
        drift_score = float(parts[0])
        drift_flag = int(parts[1])
        axis = parts[2].lower()
        return drift_score, drift_flag, axis
    except Exception:
        return None, None, None

def score(sample: Dict[str, Any], prediction: str) -> ScoreResult:
    ds, df, ax = parse(prediction or "")
    if ds is None:
        return ScoreResult(0.0, {"error":"parse failure"})

    true_ds = sample.get("overlay_drift_score","")
    true_df = sample.get("drift_flag","")
    true_ax = str(sample.get("dominant_cause_axis","")).lower()

    try:
        true_ds = float(true_ds)
        true_df = int(true_df)
    except:
        true_ds = None

    if true_ds is None:
        valid = (0 <= ds <= 1) and (df in (0,1)) and (ax in VALID_AXES)
        return ScoreResult(1.0 if valid else 0.0, {"mode":"format_only"})

    err = abs(true_ds - ds)
    s = max(0.0, 1.0 - err)
    if df == true_df:
        s += 0.20
    if ax == true_ax:
        s += 0.20

    return ScoreResult(min(1.0, s), {
        "id": sample.get("id"),
        "pred_drift_score": ds,
        "true_drift_score": true_ds,
        "pred_flag": df,
        "true_flag": true_df,
        "pred_axis": ax,
        "true_axis": true_ax
    })

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)}