| """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, | |
| }, | |
| ] | |