File size: 10,967 Bytes
7b91171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import csv
import json
import sys
from typing import Dict, List, Optional, Tuple


DEFAULT_REFERENCE_PATH = "data/tester.csv"
DEFAULT_PREDICTIONS_PATH = "predictions.csv"


def _safe_float(value, default: float = 0.0) -> float:
    try:
        return float(value)
    except (TypeError, ValueError):
        return default


def _normalize_binary(value) -> int:
    value_str = str(value).strip().lower()
    if value_str in {"1", "true", "yes", "y", "positive", "fail", "failure"}:
        return 1
    return 0


def _read_csv(path: str) -> List[Dict[str, str]]:
    with open(path, "r", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def _find_label_column(fieldnames: List[str]) -> str:
    label_candidates = [col for col in fieldnames if col.startswith("label_")]
    if len(label_candidates) == 1:
        return label_candidates[0]
    if not label_candidates:
        raise ValueError("No label column found. Expected a column starting with 'label_'.")
    raise ValueError(
        f"Multiple label columns found: {label_candidates}. Expected exactly one label column."
    )


def _find_prediction_columns(fieldnames: List[str]) -> Tuple[Optional[str], Optional[str]]:
    pred_label_candidates = [
        "prediction",
        "pred",
        "predicted_label",
        "prediction_label",
        "label_pred",
        "y_pred",
        "output",
    ]
    pred_score_candidates = [
        "prediction_score",
        "pred_score",
        "score",
        "probability",
        "prob",
        "confidence",
        "risk_score",
        "y_score",
    ]

    pred_label_col = next((c for c in pred_label_candidates if c in fieldnames), None)
    pred_score_col = next((c for c in pred_score_candidates if c in fieldnames), None)
    return pred_label_col, pred_score_col


def _index_prediction_rows(
    rows: List[Dict[str, str]], id_column: Optional[str]
) -> Dict[str, Dict[str, str]]:
    if not id_column:
        return {str(i): row for i, row in enumerate(rows)}
    return {str(row[id_column]): row for row in rows}


def _detect_join_key(
    reference_fields: List[str], prediction_fields: List[str]
) -> Optional[str]:
    preferred_keys = ["id", "row_id", "sample_id", "case_id", "record_id"]
    for key in preferred_keys:
        if key in reference_fields and key in prediction_fields:
            return key
    return None


def _build_y_true_y_pred(
    reference_rows: List[Dict[str, str]],
    prediction_rows: List[Dict[str, str]],
    label_col: str,
    pred_label_col: Optional[str],
    pred_score_col: Optional[str],
    threshold: float,
) -> Tuple[List[int], List[int], List[float], Dict[str, int], List[Dict[str, str]]]:
    if not prediction_rows:
        raise ValueError("Predictions file is empty.")

    ref_fields = list(reference_rows[0].keys())
    pred_fields = list(prediction_rows[0].keys())
    join_key = _detect_join_key(ref_fields, pred_fields)
    pred_index = _index_prediction_rows(prediction_rows, join_key)

    y_true: List[int] = []
    y_pred: List[int] = []
    y_score: List[float] = []
    matched_reference_rows: List[Dict[str, str]] = []

    matched_rows = 0
    missing_predictions = 0

    for i, ref_row in enumerate(reference_rows):
        ref_lookup = str(ref_row[join_key]) if join_key else str(i)
        pred_row = pred_index.get(ref_lookup)

        if pred_row is None:
            missing_predictions += 1
            continue

        true_label = _normalize_binary(ref_row.get(label_col, 0))

        if pred_label_col and pred_label_col in pred_row:
            pred_label = _normalize_binary(pred_row.get(pred_label_col, 0))
            pred_score = float(pred_label)
        elif pred_score_col and pred_score_col in pred_row:
            pred_score = _safe_float(pred_row.get(pred_score_col, 0.0))
            pred_label = 1 if pred_score >= threshold else 0
        else:
            raise ValueError(
                "No usable prediction column found. Provide a binary prediction column "
                "or a score column such as prediction_score."
            )

        y_true.append(true_label)
        y_pred.append(pred_label)
        y_score.append(pred_score)
        matched_reference_rows.append(ref_row)
        matched_rows += 1

    support = {
        "reference_rows": len(reference_rows),
        "prediction_rows": len(prediction_rows),
        "matched_rows": matched_rows,
        "missing_predictions": missing_predictions,
        "join_key_used": 0 if join_key is None else 1,
    }

    if matched_rows == 0:
        raise ValueError("No rows could be matched between reference and prediction files.")

    return y_true, y_pred, y_score, support, matched_reference_rows


def _confusion_matrix(y_true: List[int], y_pred: List[int]) -> Dict[str, int]:
    tp = tn = fp = fn = 0
    for truth, pred in zip(y_true, y_pred):
        if truth == 1 and pred == 1:
            tp += 1
        elif truth == 0 and pred == 0:
            tn += 1
        elif truth == 0 and pred == 1:
            fp += 1
        elif truth == 1 and pred == 0:
            fn += 1
    return {"tp": tp, "tn": tn, "fp": fp, "fn": fn}


def _accuracy(tp: int, tn: int, fp: int, fn: int) -> float:
    denom = tp + tn + fp + fn
    return (tp + tn) / denom if denom else 0.0


def _precision(tp: int, fp: int) -> float:
    denom = tp + fp
    return tp / denom if denom else 0.0


def _recall(tp: int, fn: int) -> float:
    denom = tp + fn
    return tp / denom if denom else 0.0


def _f1(precision: float, recall: float) -> float:
    denom = precision + recall
    return 2 * precision * recall / denom if denom else 0.0


def _trajectory_diagnostics(
    reference_rows: List[Dict[str, str]],
    y_true: List[int],
    y_pred: List[int],
) -> Dict[str, float]:
    if not reference_rows or "drift_gradient" not in reference_rows[0]:
        return {
            "trajectory_positive_support": 0,
            "recall_trajectory_deterioration_detection": 0.0,
            "false_stable_trajectory_rate": 0.0,
            "trajectory_label_alignment_rate": 0.0,
        }

    trajectory_positive_support = 0
    trajectory_detected_tp = 0
    trajectory_false_stable = 0
    trajectory_alignment_hits = 0

    for row, truth, pred in zip(reference_rows, y_true, y_pred):
        drift_gradient = _safe_float(row.get("drift_gradient", 0.0))
        worsening_trajectory = 1 if drift_gradient > 0 else 0

        if worsening_trajectory == 1:
            trajectory_positive_support += 1
            if pred == 1:
                trajectory_detected_tp += 1
            if pred == 0:
                trajectory_false_stable += 1

        if worsening_trajectory == truth:
            trajectory_alignment_hits += 1

    recall_trajectory_deterioration_detection = (
        trajectory_detected_tp / trajectory_positive_support
        if trajectory_positive_support
        else 0.0
    )

    false_stable_trajectory_rate = (
        trajectory_false_stable / trajectory_positive_support
        if trajectory_positive_support
        else 0.0
    )

    trajectory_label_alignment_rate = (
        trajectory_alignment_hits / len(reference_rows)
        if reference_rows
        else 0.0
    )

    return {
        "trajectory_positive_support": trajectory_positive_support,
        "recall_trajectory_deterioration_detection": recall_trajectory_deterioration_detection,
        "false_stable_trajectory_rate": false_stable_trajectory_rate,
        "trajectory_label_alignment_rate": trajectory_label_alignment_rate,
    }


def score(
    reference_path: str = DEFAULT_REFERENCE_PATH,
    predictions_path: str = DEFAULT_PREDICTIONS_PATH,
    threshold: float = 0.5,
) -> Dict[str, object]:
    reference_rows = _read_csv(reference_path)
    prediction_rows = _read_csv(predictions_path)

    if not reference_rows:
        raise ValueError("Reference file is empty.")

    label_col = _find_label_column(list(reference_rows[0].keys()))
    pred_label_col, pred_score_col = _find_prediction_columns(list(prediction_rows[0].keys()))

    y_true, y_pred, y_score, support, matched_reference_rows = _build_y_true_y_pred(
        reference_rows=reference_rows,
        prediction_rows=prediction_rows,
        label_col=label_col,
        pred_label_col=pred_label_col,
        pred_score_col=pred_score_col,
        threshold=threshold,
    )

    cm = _confusion_matrix(y_true, y_pred)
    precision = _precision(cm["tp"], cm["fp"])
    recall = _recall(cm["tp"], cm["fn"])
    accuracy = _accuracy(cm["tp"], cm["tn"], cm["fp"], cm["fn"])
    f1 = _f1(precision, recall)

    trajectory_metrics = _trajectory_diagnostics(
        reference_rows=matched_reference_rows,
        y_true=y_true,
        y_pred=y_pred,
    )

    return {
        "label_column": label_col,
        "prediction_label_column": pred_label_col,
        "prediction_score_column": pred_score_col,
        "primary_metric": "recall_trajectory_deterioration_detection",
        "secondary_metric": "false_stable_trajectory_rate",
        "threshold_transparency": {
            "score_threshold_used": threshold if pred_score_col else None,
            "threshold_applied_to_score_column": pred_score_col,
            "predictions_interpreted_as": (
                "binary labels from prediction column"
                if pred_label_col
                else "binary labels thresholded from score column"
            ),
        },
        "support": {
            **support,
            "positive_label_support": sum(y_true),
            "negative_label_support": len(y_true) - sum(y_true),
            "predicted_positive_support": sum(y_pred),
            "predicted_negative_support": len(y_pred) - sum(y_pred),
        },
        "metrics": {
            "accuracy": round(accuracy, 4),
            "precision": round(precision, 4),
            "recall": round(recall, 4),
            "f1": round(f1, 4),
            "recall_trajectory_deterioration_detection": round(
                trajectory_metrics["recall_trajectory_deterioration_detection"], 4
            ),
            "false_stable_trajectory_rate": round(
                trajectory_metrics["false_stable_trajectory_rate"], 4
            ),
            "trajectory_label_alignment_rate": round(
                trajectory_metrics["trajectory_label_alignment_rate"], 4
            ),
        },
        "confusion_matrix": cm,
        "trajectory_support": {
            "trajectory_positive_support": trajectory_metrics["trajectory_positive_support"],
        },
    }


if __name__ == "__main__":
    reference_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_REFERENCE_PATH
    predictions_path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_PREDICTIONS_PATH
    threshold = float(sys.argv[3]) if len(sys.argv) > 3 else 0.5

    output = score(
        reference_path=reference_path,
        predictions_path=predictions_path,
        threshold=threshold,
    )
    print(json.dumps(output, indent=2))