File size: 11,973 Bytes
6d32faf
 
 
 
 
 
 
 
 
 
 
6a28f91
6d32faf
 
 
 
 
f6c65ef
6d32faf
 
 
 
 
 
 
 
 
f6c65ef
6d32faf
 
 
 
 
 
f6c65ef
6d32faf
 
 
 
 
 
 
f6c65ef
6d32faf
 
 
f6c65ef
6d32faf
 
 
 
 
f6c65ef
6d32faf
 
6a28f91
 
6d32faf
 
 
 
 
f6c65ef
6d32faf
 
6a28f91
 
 
6d32faf
f6c65ef
 
6d32faf
 
 
6a28f91
 
 
 
 
 
 
 
 
 
 
 
 
f6c65ef
 
6d32faf
 
 
6a28f91
 
 
 
 
 
 
 
 
 
 
 
 
f6c65ef
 
6d32faf
 
 
6a28f91
 
 
 
 
 
 
 
 
 
 
 
 
f6c65ef
 
6d32faf
 
 
6a28f91
 
 
 
 
 
 
 
 
 
 
 
 
f6c65ef
 
6d32faf
 
 
6a28f91
 
 
 
 
 
 
 
 
 
 
 
 
f6c65ef
6d32faf
 
f6c65ef
6d32faf
f6c65ef
6d32faf
 
 
 
 
 
f6c65ef
6d32faf
 
 
 
 
 
 
f6c65ef
6a28f91
 
 
 
6d32faf
6a28f91
 
 
 
6d32faf
6a28f91
 
 
6d32faf
 
 
f6c65ef
6d32faf
f6c65ef
6d32faf
 
 
 
 
 
 
 
f6c65ef
6d32faf
 
 
 
f6c65ef
6d32faf
 
 
 
f6c65ef
6d32faf
 
 
 
 
 
 
 
 
 
 
 
 
 
f6c65ef
6d32faf
6a28f91
 
 
 
 
 
 
 
6d32faf
6a28f91
 
 
 
 
 
f6c65ef
6d32faf
6a28f91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d32faf
6a28f91
 
f6c65ef
6d32faf
f6c65ef
6d32faf
 
 
 
f6c65ef
6d32faf
f6c65ef
6d32faf
 
 
 
 
 
 
f6c65ef
6d32faf
 
 
f6c65ef
6d32faf
 
 
 
f6c65ef
6d32faf
 
f6c65ef
6d32faf
6a28f91
 
6d32faf
 
f6c65ef
6d32faf
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
"""Ripeness classifier calibration based on accuracy metrics.

Analyzes classification performance and suggests threshold adjustments
to improve accuracy over time.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

from src.monitoring.ripeness_metrics import RipenessMetrics


@dataclass
class ThresholdAdjustment:
    """Suggested threshold adjustment with reasoning."""

    threshold_name: str
    current_value: int | float
    suggested_value: int | float
    reason: str
    confidence: str  # "high", "medium", "low"


class RipenessCalibrator:
    """Analyzes ripeness metrics and suggests threshold calibration."""

    # Calibration rules thresholds
    HIGH_FALSE_POSITIVE_THRESHOLD = 0.20
    HIGH_FALSE_NEGATIVE_THRESHOLD = 0.15
    LOW_UNKNOWN_THRESHOLD = 0.05
    LOW_RIPE_PRECISION_THRESHOLD = 0.70
    LOW_UNRIPE_RECALL_THRESHOLD = 0.60

    @classmethod
    def analyze_metrics(
        cls,
        metrics: RipenessMetrics,
        current_thresholds: Optional[dict[str, int | float]] = None,
    ) -> list[ThresholdAdjustment]:
        """Analyze metrics and suggest threshold adjustments.

        Args:
            metrics: RipenessMetrics with classification history
            current_thresholds: Current threshold values (optional)

        Returns:
            List of suggested adjustments with reasoning
        """
        accuracy = metrics.get_accuracy_metrics()
        adjustments: list[ThresholdAdjustment] = []

        # Default current thresholds if not provided
        if current_thresholds is None:
            from src.core.ripeness import RipenessClassifier

            current_thresholds = {
                "MIN_SERVICE_HEARINGS": RipenessClassifier.MIN_SERVICE_HEARINGS,
                "MIN_STAGE_DAYS": RipenessClassifier.MIN_STAGE_DAYS,
                "MIN_CASE_AGE_DAYS": RipenessClassifier.MIN_CASE_AGE_DAYS,
            }

        # Check if we have enough data
        if accuracy["completed_predictions"] < 50:
            print(
                "Warning: Insufficient data for calibration (need at least 50 predictions)"
            )
            return adjustments

        # Rule 1: High false positive rate -> increase MIN_SERVICE_HEARINGS
        if accuracy["false_positive_rate"] > cls.HIGH_FALSE_POSITIVE_THRESHOLD:
            current_hearings = current_thresholds.get("MIN_SERVICE_HEARINGS", 1)
            suggested_hearings = current_hearings + 1
            adjustments.append(
                ThresholdAdjustment(
                    threshold_name="MIN_SERVICE_HEARINGS",
                    current_value=current_hearings,
                    suggested_value=suggested_hearings,
                    reason=(
                        f"False positive rate {accuracy['false_positive_rate']:.1%} exceeds "
                        f"{cls.HIGH_FALSE_POSITIVE_THRESHOLD:.0%}. Cases marked RIPE are adjourning. "
                        f"Require more hearings as evidence of readiness."
                    ),
                    confidence="high",
                )
            )

        # Rule 2: High false negative rate -> decrease MIN_STAGE_DAYS
        if accuracy["false_negative_rate"] > cls.HIGH_FALSE_NEGATIVE_THRESHOLD:
            current_days = current_thresholds.get("MIN_STAGE_DAYS", 7)
            suggested_days = max(3, current_days - 2)  # Don't go below 3 days
            adjustments.append(
                ThresholdAdjustment(
                    threshold_name="MIN_STAGE_DAYS",
                    current_value=current_days,
                    suggested_value=suggested_days,
                    reason=(
                        f"False negative rate {accuracy['false_negative_rate']:.1%} exceeds "
                        f"{cls.HIGH_FALSE_NEGATIVE_THRESHOLD:.0%}. UNRIPE cases are progressing. "
                        f"Relax stage maturity requirement."
                    ),
                    confidence="medium",
                )
            )

        # Rule 3: Low UNKNOWN rate -> system too confident, add uncertainty
        if accuracy["unknown_rate"] < cls.LOW_UNKNOWN_THRESHOLD:
            current_age = current_thresholds.get("MIN_CASE_AGE_DAYS", 14)
            suggested_age = current_age + 7
            adjustments.append(
                ThresholdAdjustment(
                    threshold_name="MIN_CASE_AGE_DAYS",
                    current_value=current_age,
                    suggested_value=suggested_age,
                    reason=(
                        f"UNKNOWN rate {accuracy['unknown_rate']:.1%} below "
                        f"{cls.LOW_UNKNOWN_THRESHOLD:.0%}. System is overconfident. "
                        f"Increase case age requirement to add uncertainty for immature cases."
                    ),
                    confidence="medium",
                )
            )

        # Rule 4: Low RIPE precision -> more conservative RIPE classification
        if accuracy["ripe_precision"] < cls.LOW_RIPE_PRECISION_THRESHOLD:
            current_hearings = current_thresholds.get("MIN_SERVICE_HEARINGS", 1)
            suggested_hearings = current_hearings + 1
            adjustments.append(
                ThresholdAdjustment(
                    threshold_name="MIN_SERVICE_HEARINGS",
                    current_value=current_hearings,
                    suggested_value=suggested_hearings,
                    reason=(
                        f"RIPE precision {accuracy['ripe_precision']:.1%} below "
                        f"{cls.LOW_RIPE_PRECISION_THRESHOLD:.0%}. Too many RIPE predictions fail. "
                        f"Be more conservative in marking cases RIPE."
                    ),
                    confidence="high",
                )
            )

        # Rule 5: Low UNRIPE recall -> missing bottlenecks
        if accuracy["unripe_recall"] < cls.LOW_UNRIPE_RECALL_THRESHOLD:
            current_days = current_thresholds.get("MIN_STAGE_DAYS", 7)
            suggested_days = current_days + 3
            adjustments.append(
                ThresholdAdjustment(
                    threshold_name="MIN_STAGE_DAYS",
                    current_value=current_days,
                    suggested_value=suggested_days,
                    reason=(
                        f"UNRIPE recall {accuracy['unripe_recall']:.1%} below "
                        f"{cls.LOW_UNRIPE_RECALL_THRESHOLD:.0%}. Missing many bottlenecks. "
                        f"Increase stage maturity requirement to catch more unripe cases."
                    ),
                    confidence="medium",
                )
            )

        # Deduplicate adjustments (same threshold suggested multiple times)
        deduplicated = cls._deduplicate_adjustments(adjustments)

        return deduplicated

    @classmethod
    def _deduplicate_adjustments(
        cls, adjustments: list[ThresholdAdjustment]
    ) -> list[ThresholdAdjustment]:
        """Deduplicate adjustments for same threshold, prefer high confidence."""
        threshold_map: dict[str, ThresholdAdjustment] = {}

        for adj in adjustments:
            if adj.threshold_name not in threshold_map:
                threshold_map[adj.threshold_name] = adj
            else:
                # Keep adjustment with higher confidence or larger change
                existing = threshold_map[adj.threshold_name]
                confidence_order = {"high": 3, "medium": 2, "low": 1}

                if (
                    confidence_order[adj.confidence]
                    > confidence_order[existing.confidence]
                ):
                    threshold_map[adj.threshold_name] = adj
                elif (
                    confidence_order[adj.confidence]
                    == confidence_order[existing.confidence]
                ):
                    # Same confidence - keep larger adjustment magnitude
                    existing_delta = abs(
                        existing.suggested_value - existing.current_value
                    )
                    new_delta = abs(adj.suggested_value - adj.current_value)
                    if new_delta > existing_delta:
                        threshold_map[adj.threshold_name] = adj

        return list(threshold_map.values())

    @classmethod
    def generate_calibration_report(
        cls,
        metrics: RipenessMetrics,
        adjustments: list[ThresholdAdjustment],
        output_path: str | None = None,
    ) -> str:
        """Generate human-readable calibration report.

        Args:
            metrics: RipenessMetrics with classification history
            adjustments: List of suggested adjustments
            output_path: Optional file path to save report

        Returns:
            Report text
        """
        accuracy = metrics.get_accuracy_metrics()

        lines = [
            "Ripeness Classifier Calibration Report",
            "=" * 70,
            "",
            "Current Performance:",
            f"  Total predictions: {accuracy['total_predictions']}",
            f"  Completed: {accuracy['completed_predictions']}",
            f"  False positive rate: {accuracy['false_positive_rate']:.1%}",
            f"  False negative rate: {accuracy['false_negative_rate']:.1%}",
            f"  UNKNOWN rate: {accuracy['unknown_rate']:.1%}",
            f"  RIPE precision: {accuracy['ripe_precision']:.1%}",
            f"  UNRIPE recall: {accuracy['unripe_recall']:.1%}",
            "",
        ]

        if not adjustments:
            lines.extend(
                [
                    "Recommended Adjustments:",
                    "  No adjustments needed - performance is within acceptable ranges.",
                    "",
                    "Current thresholds are performing well. Continue monitoring.",
                ]
            )
        else:
            lines.extend(
                [
                    "Recommended Adjustments:",
                    "",
                ]
            )

            for i, adj in enumerate(adjustments, 1):
                lines.extend(
                    [
                        f"{i}. {adj.threshold_name}",
                        f"   Current: {adj.current_value}",
                        f"   Suggested: {adj.suggested_value}",
                        f"   Confidence: {adj.confidence.upper()}",
                        f"   Reason: {adj.reason}",
                        "",
                    ]
                )

            lines.extend(
                [
                    "Implementation:",
                    "  1. Review suggested adjustments",
                    "  2. Apply using: RipenessClassifier.set_thresholds(new_values)",
                    "  3. Re-run simulation to validate improvements",
                    "  4. Compare new metrics with baseline",
                    "",
                ]
            )

        report = "\n".join(lines)

        if output_path:
            with open(output_path, "w") as f:
                f.write(report)
            print(f"Calibration report saved to {output_path}")

        return report

    @classmethod
    def apply_adjustments(
        cls,
        adjustments: list[ThresholdAdjustment],
        auto_apply: bool = False,
    ) -> dict[str, int | float]:
        """Apply threshold adjustments to RipenessClassifier.

        Args:
            adjustments: List of adjustments to apply
            auto_apply: If True, apply immediately; if False, return dict only

        Returns:
            Dictionary of new threshold values
        """
        new_thresholds: dict[str, int | float] = {}

        for adj in adjustments:
            new_thresholds[adj.threshold_name] = adj.suggested_value

        if auto_apply:
            from src.core.ripeness import RipenessClassifier

            RipenessClassifier.set_thresholds(new_thresholds)
            print(f"Applied {len(adjustments)} threshold adjustments")

        return new_thresholds