File size: 11,317 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 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 | """
Optimization Operating System — Interactive Optimization Console
Unified platform for scheduling, routing, assignment, inventory, facility location, and packing.
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import gradio as gr
import pandas as pd
import plotly.graph_objects as go
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / "src"))
from optos.constants import PROBLEM_TYPES, SIZE_PRESETS, SOLVERS # noqa: E402
from optos.pipeline import OptOSPipeline # noqa: E402
from optos.visualization import ( # noqa: E402
build_category_radar,
build_gap_timeline,
build_heatmap,
build_progress_chart,
build_scalability_chart,
build_solver_comparison_chart,
)
pipeline = OptOSPipeline(ROOT / "assets")
pipeline.load()
SUMMARY = pipeline.summary
PROBLEM_CHOICES = pipeline.problem_choices()
SIZE_CHOICES = pipeline.size_choices()
CUSTOM_CSS = """
.gradio-container { max-width: 1560px !important; }
.markdown h1 { color: #4f46e5; font-weight: 700; }
.tab-nav button { font-weight: 600; }
"""
_state: dict = {"last_run": None, "last_explanation": None, "last_scenarios": None}
def _kpi_md() -> str:
return f"""
### Optimization Operating System — Platform Overview
| Metric | Value |
|--------|-------|
| Engine version | **v{pipeline.version}** |
| Problem types | **{SUMMARY.get('problem_types', 6)}** (Scheduling, Routing, Assignment, Inventory, Facility, Packing) |
| Methods per problem | **4** (Baseline · Exact · Scalable · Robust) |
| Registered solvers | **{SUMMARY.get('solvers', 6)}** (HiGHS, CBC, CP-SAT, SCIP*, Gurobi*, Heuristic) |
| Benchmark runs | **{SUMMARY.get('total_benchmark_runs', 0)}** pre-computed |
| Instance sizes | Small · Medium · Large · Dynamic · Stochastic |
*Reference profiles — live solving uses open-source solvers on HF Spaces.*
"""
def _benchmark_df() -> pd.DataFrame:
rows = pipeline.benchmark_table_rows()
if not rows:
return pd.DataFrame()
cols = [
"problem_label", "size", "method_label", "method_category",
"objective_value", "optimality_gap", "elapsed_time_sec",
"iterations", "feasible", "winner",
]
return pd.DataFrame(rows)[[c for c in cols if c in rows[0]]]
def _run_optimization(problem_type, size, seed, time_limit):
run = pipeline.run_experiment(problem_type, size, int(seed), float(time_limit))
_state["last_run"] = run
explanation = pipeline.explain_run(run)
_state["last_explanation"] = explanation
rows = []
for r in run.results:
rows.append({
"Method": r.method_label,
"Category": r.method_category,
"Solver": r.solver_id,
"Objective": r.metrics.objective_value,
"Best Bound": r.metrics.best_bound,
"Gap (%)": r.metrics.optimality_gap,
"Time (s)": r.metrics.elapsed_time_sec,
"Iterations": r.metrics.iterations,
"Violations": r.metrics.constraint_violations,
"Feasible": r.metrics.feasible,
"Status": r.metrics.status,
"Winner": r.method_id == run.winner,
})
df = pd.DataFrame(rows)
winner_label = next((r.method_label for r in run.results if r.method_id == run.winner), run.winner)
summary_md = f"""
**Winner:** {winner_label} · **Gap vs others:** {run.winner_gap_pct:.1f}% · **Runtime:** {run.runtime_sec:.2f}s
| Solve State | Value |
|-------------|-------|
| Best feasible objective | **{min(r.metrics.objective_value for r in run.results if r.metrics.feasible):.2f}** |
| Best bound | **{max(r.metrics.best_bound for r in run.results):.2f}** |
| Min gap | **{min(r.metrics.optimality_gap for r in run.results if r.metrics.feasible):.2f}%** |
"""
chart_rows = [
{
"method_label": r.method_label,
"method_id": r.method_id,
"method_category": r.method_category,
"objective_value": r.metrics.objective_value,
"optimality_gap": r.metrics.optimality_gap,
"elapsed_time_sec": r.metrics.elapsed_time_sec,
"winner": r.method_id == run.winner,
}
for r in run.results
]
fig_cmp = build_solver_comparison_chart(chart_rows)
fig_gap = build_gap_timeline(chart_rows)
winner_r = next((r for r in run.results if r.method_id == run.winner), run.results[0])
fig_prog = build_progress_chart(winner_r.metrics.to_dict())
return df, summary_md, fig_cmp, fig_gap, fig_prog
def _run_scenarios(problem_type, size, seed):
scenarios = pipeline.run_scenarios(problem_type, size, int(seed))
_state["last_scenarios"] = scenarios
rows = []
for s in scenarios:
rows.append({
"Scenario": s.scenario_label,
"Type": s.scenario_type,
"Baseline Obj": s.baseline_objective,
"Perturbed Obj": s.perturbed_objective,
"Delta (%)": s.delta_pct,
"Feasible": s.feasible,
"Binding": ", ".join(s.binding_constraints),
})
return pd.DataFrame(rows)
def _explain_current():
exp = _state.get("last_run")
expl = _state.get("last_explanation")
if not exp or not expl:
return "Run an optimization first.", pd.DataFrame()
binding_df = pd.DataFrame(expl.binding_constraints)
shadows_df = pd.DataFrame(expl.shadow_prices)
md = f"""
### Explanation Report
**Infeasibility:** {expl.infeasibility_reason or "None — solution is feasible."}
**What-if suggestions:**
"""
for s in expl.what_if_suggestions:
md += f"- {s}\n"
md += "\n**Counterfactuals:**\n"
for c in expl.counterfactuals:
md += f"- {c.get('action')}: expected objective ≈ {c.get('expected_objective', c.get('expected_impact', 'N/A'))}\n"
return md, binding_df, shadows_df
def _export_json():
run = _state.get("last_run")
if not run:
return "No run to export."
return pipeline.export_json(run)
def _export_csv():
run = _state.get("last_run")
if not run:
return pd.DataFrame()
return pd.DataFrame(pipeline.export_csv_rows(run))
def _registry_md():
lines = ["### Model Registry\n| Problem | Category | Description |"]
lines.append("|---------|----------|-------------|")
for k, m in PROBLEM_TYPES.items():
lines.append(f"| {m['label']} | {m['category']} | {m['description']} |")
lines.append("\n### Solver Registry\n| Solver | License | Available | Strengths |")
lines.append("|--------|---------|-----------|-----------|")
for sid, s in SOLVERS.items():
avail = "✓" if s["available"] else "ref"
lines.append(f"| {s['label']} | {s['license']} | {avail} | {', '.join(s['strengths'])} |")
return "\n".join(lines)
def _methods_table(problem_type):
info = pipeline.method_info(problem_type)
return pd.DataFrame(info)
with gr.Blocks(title="Optimization Operating System", css=CUSTOM_CSS) as demo:
gr.Markdown("# Optimization Operating System")
gr.Markdown("Unified **Optimization-as-a-Service** platform — receive, solve, compare, and explain optimization problems across scheduling, routing, assignment, inventory, facility location, and packing.")
with gr.Tab("Executive Overview"):
gr.Markdown(_kpi_md())
gr.Dataframe(value=_benchmark_df(), label="Pre-computed Benchmark Summary", interactive=False)
fig_heat = build_heatmap(pipeline.comparisons)
gr.Plot(fig_heat, label="Cross-Problem Benchmark Heatmap")
fig_scale = build_scalability_chart(pipeline.scalability.get("rows", []))
gr.Plot(fig_scale, label="Scalability Profile")
with gr.Tab("Run Optimization"):
with gr.Row():
problem_dd = gr.Dropdown(PROBLEM_CHOICES, value="scheduling", label="Problem Type")
size_dd = gr.Dropdown(SIZE_CHOICES, value="medium", label="Instance Size")
seed_num = gr.Number(value=42, label="Seed", precision=0)
time_limit = gr.Slider(5, 60, value=15, step=1, label="Time Limit (s)")
run_btn = gr.Button("Run All Methods", variant="primary")
run_summary = gr.Markdown()
run_table = gr.DataFrame(label="Method Comparison", interactive=False)
with gr.Row():
cmp_plot = gr.Plot(label="Objective Comparison")
gap_plot = gr.Plot(label="Gap vs Time")
prog_plot = gr.Plot(label="Solve Progress")
methods_preview = gr.DataFrame(label="Registered Methods", value=_methods_table("scheduling"))
problem_dd.change(fn=_methods_table, inputs=problem_dd, outputs=methods_preview)
run_btn.click(
fn=_run_optimization,
inputs=[problem_dd, size_dd, seed_num, time_limit],
outputs=[run_table, run_summary, cmp_plot, gap_plot, prog_plot],
)
with gr.Tab("Scenario Engine"):
gr.Markdown("Stress-test instances with capacity changes, demand shifts, resource removal, cost increases, and network disruptions.")
with gr.Row():
sc_problem = gr.Dropdown(PROBLEM_CHOICES, value="routing", label="Problem Type")
sc_size = gr.Dropdown(SIZE_CHOICES, value="medium", label="Size")
sc_seed = gr.Number(value=42, label="Seed", precision=0)
sc_btn = gr.Button("Run All Scenarios", variant="primary")
sc_table = gr.DataFrame(label="Scenario Results", interactive=False)
sc_btn.click(fn=_run_scenarios, inputs=[sc_problem, sc_size, sc_seed], outputs=sc_table)
with gr.Tab("Explanation Engine"):
gr.Markdown("Binding constraints, shadow prices, infeasibility analysis, and what-if suggestions.")
explain_btn = gr.Button("Explain Last Run", variant="primary")
explain_md = gr.Markdown()
with gr.Row():
binding_df = gr.DataFrame(label="Binding Constraints", interactive=False)
shadow_df = gr.DataFrame(label="Shadow Prices", interactive=False)
explain_btn.click(fn=_explain_current, outputs=[explain_md, binding_df, shadow_df])
with gr.Tab("Benchmarks"):
gr.Dataframe(value=_benchmark_df(), label="Full Benchmark Table", interactive=False)
fig_radar = build_category_radar(pipeline.benchmark_table_rows())
gr.Plot(fig_radar, label="Method Category Radar")
fig_scale2 = build_scalability_chart(pipeline.scalability.get("rows", []))
gr.Plot(fig_scale2, label="Scalability")
with gr.Tab("Registry"):
gr.Markdown(_registry_md())
with gr.Tab("Export"):
gr.Markdown("Download results from the last optimization run as JSON or CSV.")
export_json_btn = gr.Button("Preview JSON Export")
export_json_out = gr.Code(language="json", label="JSON Result")
export_csv_btn = gr.Button("Preview CSV Export")
export_csv_out = gr.DataFrame(label="CSV Rows")
export_json_btn.click(fn=_export_json, outputs=export_json_out)
export_csv_btn.click(fn=_export_csv, outputs=export_csv_out)
if __name__ == "__main__":
demo.launch()
|