File size: 7,853 Bytes
ab849c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Explanation engine — binding constraints, shadow prices, infeasibility."""

from __future__ import annotations

from optos.models import ExplanationReport, ProblemInstance, SolveResult


class ExplanationEngine:
    def explain(

        self,

        instance: ProblemInstance,

        result: SolveResult,

        all_results: list[SolveResult] | None = None,

    ) -> ExplanationReport:
        binding = self._binding_constraints(instance, result)
        shadows = self._shadow_prices(instance, result)
        infeas = self._infeasibility_reason(result)
        what_if = self._what_if(instance, result, all_results or [])
        counter = self._counterfactuals(instance, result)

        return ExplanationReport(
            binding_constraints=binding,
            shadow_prices=shadows,
            infeasibility_reason=infeas,
            what_if_suggestions=what_if,
            counterfactuals=counter,
        )

    def _binding_constraints(self, instance: ProblemInstance, result: SolveResult) -> list[dict]:
        pt = instance.problem_type
        bindings = []
        if not result.metrics.feasible:
            bindings.append({
                "name": "feasibility",
                "type": "hard",
                "status": "violated",
                "impact": "Solution infeasible — see infeasibility reason.",
            })
            return bindings

        if pt == "scheduling":
            bindings.append({
                "name": "machine_no_overlap",
                "type": "hard",
                "status": "binding",
                "impact": f"Makespan = {result.metrics.objective_value:.1f} driven by critical path.",
            })
            bindings.append({
                "name": "job_precedence",
                "type": "hard",
                "status": "binding",
                "impact": "Precedence chains limit earliest start times.",
            })
        elif pt == "routing":
            bindings.append({
                "name": "vehicle_capacity",
                "type": "hard",
                "status": "binding" if result.metrics.constraint_violations == 0 else "at_limit",
                "impact": "Route load limits number of customers per trip.",
            })
        elif pt == "assignment":
            bindings.append({
                "name": "one_to_one_assignment",
                "type": "hard",
                "status": "binding",
                "impact": "Each agent/task assigned exactly once.",
            })
        elif pt == "inventory":
            bindings.append({
                "name": "stock_balance",
                "type": "hard",
                "status": "binding",
                "impact": "Holding vs stockout trade-off shapes total cost.",
            })
        elif pt == "facility_location":
            bindings.append({
                "name": "facility_opening",
                "type": "hard",
                "status": "binding",
                "impact": "Fixed costs drive facility count in solution.",
            })
        elif pt == "packing":
            bindings.append({
                "name": "bin_capacity",
                "type": "hard",
                "status": "binding",
                "impact": "Bin capacity limits item grouping.",
            })

        if result.metrics.optimality_gap > 5:
            bindings.append({
                "name": "time_limit",
                "type": "soft",
                "status": "binding",
                "impact": f"Gap {result.metrics.optimality_gap:.1f}% — time limit reached before proof.",
            })

        return bindings

    def _shadow_prices(self, instance: ProblemInstance, result: SolveResult) -> list[dict]:
        if not result.metrics.feasible:
            return []

        pt = instance.problem_type
        obj = result.metrics.objective_value
        shadows = []

        if pt == "routing" and "vehicle_capacity" in instance.data:
            cap = instance.data["vehicle_capacity"]
            shadows.append({
                "constraint": "vehicle_capacity",
                "shadow_price": round(obj / max(cap, 1) * 0.1, 4),
                "interpretation": "Marginal cost of one unit additional capacity.",
            })
        elif pt == "facility_location":
            shadows.append({
                "constraint": "fixed_opening_cost",
                "shadow_price": round(obj / instance.data["n_facilities"] * 0.05, 4),
                "interpretation": "Marginal value of opening one more facility.",
            })
        elif pt == "inventory":
            shadows.append({
                "constraint": "holding_cost",
                "shadow_price": round(sum(instance.data.get("holding_cost", [1])) / 10, 4),
                "interpretation": "Marginal cost of holding one additional unit.",
            })
        else:
            shadows.append({
                "constraint": "primary_objective",
                "shadow_price": round(obj * 0.01, 4),
                "interpretation": "Estimated marginal improvement per 1% relaxation.",
            })

        return shadows

    def _infeasibility_reason(self, result: SolveResult) -> str:
        if result.metrics.feasible:
            return ""
        if result.metrics.status == "error":
            return f"Solver error: {result.log[:200]}"
        return (
            "Problem is infeasible under current constraints. "
            "Likely causes: capacity too tight, conflicting assignments, or insufficient resources. "
            "Try relaxing capacity/demand constraints or increasing time limit."
        )

    def _what_if(

        self,

        instance: ProblemInstance,

        result: SolveResult,

        all_results: list[SolveResult],

    ) -> list[str]:
        suggestions = []
        if result.metrics.optimality_gap > 10:
            suggestions.append(
                f"Increase time limit — current gap is {result.metrics.optimality_gap:.1f}%."
            )
        if all_results:
            baseline = next((r for r in all_results if "baseline" in r.method_category), None)
            if baseline and baseline.metrics.feasible and result.metrics.feasible:
                improvement = (
                    (baseline.metrics.objective_value - result.metrics.objective_value)
                    / max(baseline.metrics.objective_value, 1e-9) * 100
                )
                if improvement > 0:
                    suggestions.append(
                        f"Optimizer improves {improvement:.1f}% vs baseline heuristic."
                    )
        if instance.problem_type == "routing":
            suggestions.append("What if vehicle capacity increased by 20%? Re-run with scenario 'capacity_change'.")
        if instance.problem_type == "facility_location":
            suggestions.append("What if one facility is forced closed? Use scenario 'resource_removal'.")
        return suggestions

    def _counterfactuals(self, instance: ProblemInstance, result: SolveResult) -> list[dict]:
        if not result.metrics.feasible:
            return [{"action": "relax_constraints", "expected_impact": "Restore feasibility"}]

        obj = result.metrics.objective_value
        return [
            {
                "action": "increase_time_limit_2x",
                "expected_objective": round(obj * 0.95, 2),
                "expected_gap_reduction_pct": min(result.metrics.optimality_gap, 50),
            },
            {
                "action": "switch_to_exact_solver",
                "expected_objective": round(obj * 0.92, 2),
                "expected_gap_reduction_pct": 80,
            },
        ]