|
| 1 | +import threading |
| 2 | +import tkinter as tk |
| 3 | +from tkinter import ttk, messagebox |
| 4 | +from typing import Optional |
| 5 | + |
| 6 | +import matplotlib |
| 7 | +matplotlib.use("TkAgg") |
| 8 | +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg |
| 9 | +import matplotlib.pyplot as plt |
| 10 | + |
| 11 | +from .simulated_annealing import SimulatedAnnealing |
| 12 | +from .example import example_functions |
| 13 | + |
| 14 | + |
| 15 | +class SA_GUI(tk.Tk): |
| 16 | + def __init__(self): |
| 17 | + super().__init__() |
| 18 | + self.title("Simulated Annealing Explorer") |
| 19 | + self.geometry("800x600") |
| 20 | + |
| 21 | + # Left: controls |
| 22 | + ctrl = ttk.Frame(self) |
| 23 | + ctrl.pack(side=tk.LEFT, fill=tk.Y, padx=8, pady=8) |
| 24 | + |
| 25 | + ttk.Label(ctrl, text="Function:").pack(anchor=tk.W) |
| 26 | + self.func_var = tk.StringVar(value="sphere") |
| 27 | + func_menu = ttk.Combobox(ctrl, textvariable=self.func_var, values=list(example_functions.keys()), state="readonly") |
| 28 | + func_menu.pack(fill=tk.X) |
| 29 | + |
| 30 | + ttk.Label(ctrl, text="Initial (comma-separated)").pack(anchor=tk.W, pady=(8, 0)) |
| 31 | + self.init_entry = ttk.Entry(ctrl) |
| 32 | + self.init_entry.insert(0, "5, -3") |
| 33 | + self.init_entry.pack(fill=tk.X) |
| 34 | + |
| 35 | + ttk.Label(ctrl, text="Bounds (lo:hi comma-separated for each)").pack(anchor=tk.W, pady=(8, 0)) |
| 36 | + self.bounds_entry = ttk.Entry(ctrl) |
| 37 | + self.bounds_entry.insert(0, "-10:10, -10:10") |
| 38 | + self.bounds_entry.pack(fill=tk.X) |
| 39 | + |
| 40 | + ttk.Label(ctrl, text="Temperature").pack(anchor=tk.W, pady=(8, 0)) |
| 41 | + self.temp_entry = ttk.Entry(ctrl) |
| 42 | + self.temp_entry.insert(0, "50") |
| 43 | + self.temp_entry.pack(fill=tk.X) |
| 44 | + |
| 45 | + ttk.Label(ctrl, text="Cooling rate").pack(anchor=tk.W, pady=(8, 0)) |
| 46 | + self.cool_entry = ttk.Entry(ctrl) |
| 47 | + self.cool_entry.insert(0, "0.95") |
| 48 | + self.cool_entry.pack(fill=tk.X) |
| 49 | + |
| 50 | + ttk.Label(ctrl, text="Iterations per temp").pack(anchor=tk.W, pady=(8, 0)) |
| 51 | + self.iter_entry = ttk.Entry(ctrl) |
| 52 | + self.iter_entry.insert(0, "200") |
| 53 | + self.iter_entry.pack(fill=tk.X) |
| 54 | + |
| 55 | + self.run_btn = ttk.Button(ctrl, text="Run", command=self._on_run) |
| 56 | + self.run_btn.pack(fill=tk.X, pady=(12, 0)) |
| 57 | + |
| 58 | + self.stop_flag = threading.Event() |
| 59 | + self.stop_btn = ttk.Button(ctrl, text="Stop", command=self._on_stop, state=tk.DISABLED) |
| 60 | + self.stop_btn.pack(fill=tk.X, pady=(6, 0)) |
| 61 | + |
| 62 | + # Right: plot |
| 63 | + fig, self.ax = plt.subplots(figsize=(5, 4)) |
| 64 | + self.fig = fig |
| 65 | + self.canvas = FigureCanvasTkAgg(fig, master=self) |
| 66 | + self.canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=1) |
| 67 | + |
| 68 | + self._plot_line, = self.ax.plot([], [], label="best_cost") |
| 69 | + self.ax.set_xlabel("Iterations") |
| 70 | + self.ax.set_ylabel("Best cost") |
| 71 | + self.ax.grid(True) |
| 72 | + |
| 73 | + def _parse_initial(self) -> list: |
| 74 | + raw = self.init_entry.get().strip() |
| 75 | + parts = [p.strip() for p in raw.split(",") if p.strip()] |
| 76 | + return [float(p) for p in parts] |
| 77 | + |
| 78 | + def _parse_bounds(self, dim: int): |
| 79 | + raw = self.bounds_entry.get().strip() |
| 80 | + parts = [p.strip() for p in raw.split(",") if p.strip()] |
| 81 | + bounds = [] |
| 82 | + for p in parts: |
| 83 | + if ":" in p: |
| 84 | + lo, hi = p.split(":", 1) |
| 85 | + bounds.append((float(lo), float(hi))) |
| 86 | + else: |
| 87 | + # single number -> symmetric |
| 88 | + val = float(p) |
| 89 | + bounds.append((-abs(val), abs(val))) |
| 90 | + # if fewer provided, extend with wide bounds |
| 91 | + while len(bounds) < dim: |
| 92 | + bounds.append((-1e6, 1e6)) |
| 93 | + return bounds[:dim] |
| 94 | + |
| 95 | + def _on_run(self): |
| 96 | + try: |
| 97 | + initial = self._parse_initial() |
| 98 | + except Exception as e: |
| 99 | + messagebox.showerror("Input error", f"Invalid initial: {e}") |
| 100 | + return |
| 101 | + |
| 102 | + func_name = self.func_var.get() |
| 103 | + func = example_functions.get(func_name) |
| 104 | + if func is None: |
| 105 | + messagebox.showerror("Input error", "Unknown function") |
| 106 | + return |
| 107 | + |
| 108 | + try: |
| 109 | + temp = float(self.temp_entry.get()) |
| 110 | + cooling = float(self.cool_entry.get()) |
| 111 | + iterations = int(self.iter_entry.get()) |
| 112 | + except Exception as e: |
| 113 | + messagebox.showerror("Input error", f"Invalid numeric param: {e}") |
| 114 | + return |
| 115 | + |
| 116 | + bounds = self._parse_bounds(len(initial)) |
| 117 | + |
| 118 | + self.run_btn.config(state=tk.DISABLED) |
| 119 | + self.stop_btn.config(state=tk.NORMAL) |
| 120 | + self.stop_flag.clear() |
| 121 | + |
| 122 | + def worker(): |
| 123 | + sa = SimulatedAnnealing(func, initial, bounds=bounds, temperature=temp, cooling_rate=cooling, iterations_per_temp=iterations) |
| 124 | + best, cost, history = sa.optimize() |
| 125 | + # update plot on main thread |
| 126 | + self.after(0, lambda: self._on_complete(best, cost, history)) |
| 127 | + |
| 128 | + t = threading.Thread(target=worker, daemon=True) |
| 129 | + t.start() |
| 130 | + |
| 131 | + def _on_stop(self): |
| 132 | + # currently we don't have a cooperative stop in the algorithm; inform user |
| 133 | + messagebox.showinfo("Stop", "Stop requested, but immediate stop is not implemented. The run will finish current loop.") |
| 134 | + |
| 135 | + def _on_complete(self, best, cost, history): |
| 136 | + x = list(range(len(history.get("best_costs", [])))) |
| 137 | + y = history.get("best_costs", []) |
| 138 | + self.ax.clear() |
| 139 | + self.ax.plot(x, y, label="best_cost") |
| 140 | + self.ax.set_xlabel("Iterations") |
| 141 | + self.ax.set_ylabel("Best cost") |
| 142 | + self.ax.grid(True) |
| 143 | + self.ax.legend() |
| 144 | + self.canvas.draw() |
| 145 | + |
| 146 | + messagebox.showinfo("Done", f"Best cost: {cost:.6g}\nBest solution: {best}") |
| 147 | + self.run_btn.config(state=tk.NORMAL) |
| 148 | + self.stop_btn.config(state=tk.DISABLED) |
| 149 | + |
| 150 | + |
| 151 | +def main(): |
| 152 | + app = SA_GUI() |
| 153 | + app.mainloop() |
| 154 | + |
| 155 | + |
| 156 | +if __name__ == "__main__": |
| 157 | + main() |
0 commit comments